本文讲述了C#调用C的方法!具有很好的参考价值,希望对大家有所帮助。一起跟随六星小编过来看看吧,具体如下:
指定的函数没有导出,检查c/c++的函数是否导出
引入的dll动态库和 exe程序的平台不一致。
c#默认的解决方案平台是AnyCPU ,如果在 x64的操作系统上运行,则是调用x64的标准库,如果c/c++默认的平台是x86,那么就会在运行的时候报该错误,
解决方案:在c#程序指定与c/c++动态库相同的平台即可。
#ifdef __cplusplus extern "C"{ #endif // __cplusplus _declspec(dllexport) //通过C语言格式导出函数,如果是在C++项目中,导出C语言格式函数需要 extern "C" int Add(int num1, int num2, int* pSum) { if (pSum == NULL) { pSum = (int*)malloc(sizeof(int)); if (pSum == NULL) { return -1; } } *pSum = num1 + num2; return 0; }
```c# public class Class2 { private const string dllPath = @"xxxx.dll"; [DllImport(dllPath, EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)] //Cdecl表示C语言格式导出的函数, EntryPoint 指定导出函数的函数名 public static extern int Add1(int num1, int num2, out int sum); //Add1 如果没有指定EntryPoint,则必须与导出函数名一致 public static void TestAdd() { Class2.Add1(100, 100, out int sum); Console.WriteLine(sum); } } ```
public class Class2 { private const string dllPath = @"xxxx.dll"; [DllImport(dllPath, EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)] //Cdecl表示C语言格式导出的函数, EntryPoint 指定导出函数的函数名 public static extern int Add2(int num1, int num2, IntPtr sum); //Add1 如果没有指定EntryPoint,则必须与导出函数名一致 public static void TestAdd() { IntPtr intPtr = Marshal.AllocHGlobal(sizeof(int)); //在非托管堆上开辟内存空间,大小为sizeof(int) if(intPtr != IntPtr.Zero && 0 == Class2.Add2(100, 100, intPtr)) { int sum1 = Marshal.PtrToStructure<int>(intPtr); //从非托管堆地址中,读取一个int空间的值 Console.WriteLine(sum1); Marshal.FreeHGlobal(intPtr); //手动释放内存空间 } } }
更多相关技术内容咨询欢迎前往并持续关注六星社区了解详情。
想高效系统的学习Python编程语言,推荐大家关注一个微信公众号:Python编程学习圈。每天分享行业资讯、技术干货供大家阅读,关注即可免费领取整套Python入门到进阶的学习资料以及教程,感兴趣的小伙伴赶紧行动起来吧。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!