C#DllImport库是用C ++编写的

时间:2012-06-25 11:51:01

标签: c# dll dllimport

我是C#的新手。 我自己用C ++编写了Dll,我将在C#app中使用该dll中的函数。

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

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

然后我尝试在C#app中导入此方法:

[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。有谁可以帮助我?

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:3)

您正在定义没有extern“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

答案 2 :(得分:2)

你是否宣布

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

在c ++代码中 - C#只能访问C而不是C ++函数。