3

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

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

这些函数在内部使用 MFC 类,所以我必须做什么才能使用 P/Invoke 在 C# 中使用 DLL。

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

4

2 回答 2

10

在标头中有此声明:

__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);

另一种选择是使用模块定义文件

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);
于 2009-11-19T13:28:00.840 回答
2

MFC 扩展 DLL 需要调用方中的 CWinApp 对象。你在 C# 中没有一个。使用具有 CWinApp 对象的 MFC 常规 DLL 包装 DLL。

于 2009-11-19T17:16:22.507 回答