C#DllImport MFC扩展DLL&名字莽莽

时间:2009-11-19 13:01:53

标签: c# c++ dll mfc dllimport

我有一个MFC扩展DLL,我想在C#应用程序中使用它。我正在公开的函数是C函数,即我像这样导出它们

extern "C"
{
 __declspec(dllexport) bool Initialize();
}

函数内部使用MFC类,所以我需要做什么才能在C#中使用P / Invoke来使用DLL。

其次,我想使用函数重载,但据我所知,C不支持函数重载,如果我导出C ++函数,它们将被破坏。那么我能解决这个问题呢?我们可以使用 DllImport 来导入C ++受损函数。

2 个答案:

答案 0 :(得分:9)

在标题中包含此声明:

__declspec(dllexport) int fnunmanaged(void);
__declspec(dllexport) int fnunmanaged(int);

您可以使用dumpbin.exe获取该函数的确切名称:

dumpbin.exe /exports unmanaged.dll

Microsoft (R) COFF/PE Dumper Version 9.00.30729.01
Copyright (C) Microsoft Corporation.  All rights reserved.


Dump of file unmanaged.dll

File Type: DLL

  Section contains the following exports for unmanaged.dll

    00000000 characteristics
    4B0546C3 time date stamp Thu Nov 19 14:23:15 2009
        0.00 version
           1 ordinal base
           2 number of functions
           2 number of names

    ordinal hint RVA      name

          1    0 0001106E ?fnunmanaged@@YAHH@Z = @ILT+105(?fnunmanaged@@YAHH@Z)
          2    1 00011159 ?fnunmanaged@@YAHXZ = @ILT+340(?fnunmanaged@@YAHXZ)

  Summary

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

在声明函数时使用此名称:

[DllImport(@"D:\work\unmanaged.dll",
    EntryPoint = "?fnunmanaged@@YAHH@Z",
    ExactSpelling = true)]
static extern int fnunmanaged();

[DllImport(@"D:\work\unmanaged.dll",
    EntryPoint = "?fnunmanaged@@YAHXZ",
    ExactSpelling = true)]
static extern int fnunmanaged(int a);

另一种选择是使用module definition file

LIBRARY "unmanaged"
EXPORTS 
  fn1=?fnunmanaged@@YAHH@Z
  fn2=?fnunmanaged@@YAHXZ

在这种情况下,您不再需要使用__declspec(dllexport),并且您的头文件可能如下所示:

int fnunmanaged(void);
int fnunmanaged(int);

最后导入它们:

[DllImport(@"D:\work\unmanaged.dll")]
static extern int fn1();

[DllImport(@"D:\work\unmanaged.dll")]
static extern int fn2(int a);

答案 1 :(得分:2)

MFC扩展DLL期望调用者中有CWinApp对象。你在C#中没有一个。 使用MFC常规DLL包装DLL,该DLL具有CWinApp对象。

相关问题