C#错误在DLLImport中查找方法 [英] C# Error Finding Method in DLLImport
问题描述
我有一个C + +汇编,我使用DLLImport导入。
I have a C++ assembly that I am importing using DLLImport.
我试图调用其方法:
namespace Testing
{
class Test{
int Run(char* filePath, bool bEntry, double duration){//code}
};
}
由
[DllImport(dllName, CharSet = CharSet.Auto)]
public static extern int Run(string filePath, bool bEntry, double duration)
);
当我调用它的方法时,我得到错误信息:
When I call its method, I get the error message:
无法找到名为Run in dll的入口点
推荐答案
运行看起来是一个非静态类方法。虽然,可以从C#调用这样的方法,这不是主要的用例。如果你通过COM暴露它,或者至少作为一个简单的C接口,它将更容易从.NET消费。
The "Run" looks to be a non-static class method. Although, it's possible to call such methods from C# this is not the primary use-case. It would be way easier to consume it from .NET if you expose it via COM, or at-least as a plain C interface:
extern "C" __declspec(dllexport) void* Testing_Test_Create();
extern "C" __declspec(dllexport) void Testing_Test_Destroy(void* self);
extern "C" __declspec(dllexport) int Testing_Test_Run(void* self, char* filePath, bool bEntry, double duration);
这里是一个如何从C#调用C ++类方法的示例:
And here is a sample how to call C++ class methods from C#:
// Test.cpp in NativeLib.dll
namespace Testing
{
class __declspec(dllexport) Test
{
public:
explicit Test(int data)
: data(data)
{
}
int Run(char const * path)
{
return this->data + strlen(path);
}
private:
int data;
};
}
// Program.cs in CSharpClient.exe
class Program
{
[DllImport(
"NativeLib.dll",
EntryPoint = "??0Test@Testing@@QAE@H@Z",
CallingConvention = CallingConvention.ThisCall,
CharSet = CharSet.Ansi)]
public static extern void TestingTestCtor(IntPtr self, int data);
[DllImport(
"NativeLib.dll",
EntryPoint = "?Run@Test@Testing@@QAEHPBD@Z",
CallingConvention = CallingConvention.ThisCall,
CharSet = CharSet.Ansi)]
public static extern int TestingTestRun(IntPtr self, string path);
static void Main(string[] args)
{
var test = Marshal.AllocCoTaskMem(4);
TestingTestCtor(test, 10);
var result = TestingTestRun(test, "path");
Console.WriteLine(result);
Marshal.FreeCoTaskMem(test);
}
}
入口点名称可能不同您的构建配置/编译器,因此使用dumpbin实用程序来获取它们。同样,这只是一个概念的证明,在实际代码中,最好使用COM。
Entry point names might be different for your build configuration/compiler, so use dumpbin utility to obtain them. Again, this is just a proof of concept, in real code it would be better to use COM.
这篇关于C#错误在DLLImport中查找方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!