如何从C++DLL中的C#简单函数调用

How to call from C# simple function in C++ DLL

本文关键字:简单 函数调用 中的 C++DLL      更新时间:2023-10-16

我在c++中有一个简单的函数(不是类的方法)

__declspec(dllexport) extern "C" void __stdcall TestFunc();  

我试着从c#调用它:

[DllImport("ImportTest.dll")]  
public static extern void TestFunc();  
...  
TestFunc();

它抛出一个"找不到入口点"异常。

怎么了?

谢谢你帮我:)

Try(猜测,DLL是在VS中编写的)

extern "C" __declspec(dllexport) void __stdcall TestFunc();

那就是:

  • __declspec(dllexport)通知编译器,此函数将从DLL导出
  • extern "C"主要防止函数名称的修饰
  • __stdcall,因为如果在[DllImport]指令中指定none,这是默认的调用约定

以后,您可以使用DLL导出查看器检查您的函数是否从DLL导出。

在C++函数中,在标头处(如果函数在标头中声明)添加

extern "C" _declspec(dllexport) void TestFunc();

在函数定义中使用

_declspec(dllexport) void TestFunc()
{
}

在C#端,您需要声明一个类似的函数

[DllImport(@"ImportTest.dll",
EntryPoint = "TestFunc",
ExactSpelling = false,
CallingConvention = CallingConvention.Cdecl)]
static extern void NewTestFunc()

现在使用,NewTestFunc()