繁体   English   中英

用C ++编写的C#DllImport库

[英]C# DllImport library written on C++

我在C#中很新。 我自己用C ++编写了Dll,我将在C#应用程序中使用该dll中的函数。

因此,在C ++项目中声明函数时,我将执行以下操作:

public static __declspec(dllexport) int captureCamera(int& captureId);

然后,我尝试在C#应用程序中导入此方法:

[DllImport("MyLib.dll")]
public static extern int captureCamera(ref int captureId);

但我有一个例外:

Unable to find an entry point named 'captureCamera' in DLL 'MyLib.dll'.

任务是在不指定EntryPoint参数的情况下执行dllimport。 有人可以帮我吗?

public static __declspec(dllexport) int captureCamera(int& captureId);

那是方法吗? 如果它是函数,则它不能是静态的,因为staticdllexport是互斥的。

和名字被改头换面。 请参阅http://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B_Name_Mangling 如果您可以获取错误的名称,然后为其提供DllImportEntryPoint=MANGLED_NAME ),则它应该可以工作。

您可以为链接器提供.def文件,其中包含导出函数的定义,然后它们的名称就不会被篡改:

Project.def:

EXPORTS
    captureCamera @1

你在申报吗

extern "C" {
    __declspec(dllexport) int captureCamera(int& captureId);
}

在您的C ++代码中-C#仅能访问C,而不能访问C ++函数。

您正在定义不带外部“ C”块的C ++函数。 由于C ++允许您重载函数(即使用不同的参数集创建许多captureCamera()函数),因此DLL中的实际函数名称将有所不同。 您可以通过打开Visual Studio命令提示符,转到二进制目录并运行以下命令进行检查:

dumpbin /exports YourDll.dll

您将获得如下内容:

Dump of file debug\dll1.dll

File Type: DLL

  Section contains the following exports for dll1.dll

    00000000 characteristics
    4FE8581B time date stamp Mon Jun 25 14:22:51 2012
        0.00 version
           1 ordinal base
           1 number of functions
           1 number of names

    ordinal hint RVA      name

          1    0 00011087 ?captureCamera@@YAHAAH@Z = @ILT+130(?captureCamera@@YAHAAH@Z)

  Summary

        1000 .data
        1000 .idata
        2000 .rdata
        1000 .reloc
        1000 .rsrc
        4000 .text
       10000 .textbss

?captureCamera @@ YAHAAH @ Z是错误的名称,实际上对您指定的参数进行编码。

如其他答案所述,只需将extern“ C”添加到声明中:

extern "C" __declspec(dllexport) int captureCamera(int& captureId)
{
    ...
}

您可以通过重新运行dumpbin来重新检查名称是否正确:

Dump of file debug\dll1.dll

File Type: DLL

  Section contains the following exports for dll1.dll

    00000000 characteristics
    4FE858FC time date stamp Mon Jun 25 14:26:36 2012
        0.00 version
           1 ordinal base
           1 number of functions
           1 number of names

    ordinal hint RVA      name

          1    0 000110B4 captureCamera = @ILT+175(_captureCamera)

  Summary

        1000 .data
        1000 .idata
        2000 .rdata
        1000 .reloc
        1000 .rsrc
        4000 .text
       10000 .textbss

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM