在C#项目中使用C ++ DLL
我有一个C ++ DLL,它必须集成在一个C#项目中。
我想我找到了正确的方法,但是调用dll会给我这个错误:System.BadImageFormatException:试图加载一个格式不正确的程序。 (HRESULTexception:0x8007000B)
这是dll中的函数:
extern long FAR PASCAL convert (LPSTR filename);
这是我在C#中使用的代码
namespace Test{ public partial class Form1 : Form { [DllImport("convert.dll", SetLastError = true)] static extern Int32 convert([MarshalAs(UnmanagedType.LPStr)] string filename); private void button1_Click(object sender, EventArgs e) { // generate textfile string filename = "testfile.txt"; StreamWriter sw = new StreamWriter(filename); sw.WriteLine("line1"); sw.WriteLine("line2"); sw.Close(); // add checksum Int32 ret = 0; try { ret = convert(filename); Console.WriteLine("Result of DLL: {0}", ret.ToString()); } catch (Exception ex) { lbl.Text = ex.ToString(); } } }}
有关如何进行此操作的任何想法?
非常感谢,弗兰克
尝试在从DLL导出的函数中使用__stdcall
(或WINAPI
或APIENTRY
)。
尝试将您的C#代码从AnyCPU切换到x86(在“属性”对话框中)。
导出的函数使用PASCAL
调用约定,在Windows中与stdcall
相同。 .Net运行时需要知道这一点,因此修改您的C#方法签名如下:
[DllImport("convert.dll", SetLastError = true, CallingConvention=CallingConvention.StdCall)] static extern Int32 convert([MarshalAs(UnmanagedType.LPStr)] string filename);
涉及的两个主要步骤是
1-创建C ++ DLL
在视觉工作室
**New->Project->Class Library** in c++ template Name of project here is first_dll in visual studio 2010. Now **declare your function as public** in first_dll.h file and write the code in first_dll.cpp file as shown below.
头文件
Cpp文件
Check **Project-> Properties -> Configuration/General -> Configuration Type** this option should be **Dynamic Library(.dll)** and build the solution/project now.
first_dll.dll文件在Debug文件夹中创建
2-在C#项目中链接它
打开C#项目
Rightclick on project name in solution explorer -> Add -> References -> Browse to path where first_dll.dll is created and add the file
在C#项目的顶部添加此行
Using first_dll;
现在可以在某些函数中使用下面的语句访问文件
double var = Class1.sum(4,5);
我将VS2010中创建的C ++项目.dll链接到VS2013中创建的C#项目。 它运作良好。