我知道这个问题以前曾多次问过这个问题。我已经阅读了所有可以找到的问题以及Stackoverflow之外的信息。到目前为止,我还没有找到答案,我可以弄清楚可以解决我遇到的具体问题。
这是非托管C DLL标头文件的代码。
namespace MyWin32DLL
{
class MyWin32ClassOne
{
public:
static __declspec(dllexport) int Getvar();
};
}
这是C DLL CPP文件的代码
#include "MyWin32ClassOne.h"
namespace MyWin32DLL
{
int MyWin32ClassOne::Getvar()
{
return 123;
}
}
我从各种来源组合在一起的代码可能根本不正确。我对C 或DLL的经验不太经验。
这是我愚蠢的小c#winforms prog的代码,我试图访问dll。(在评论中由Tolanj指出的编辑为校正类型不匹配)
namespace TestDll
{
public partial class Form1 : Form
{
[DllImport("MyWin32CppDll.dll", CallingConvention = CallingConvention.StdCall)]
public static extern int Getvar();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string response = Getvar().ToString();
MessageBox.Show(response, "title", MessageBoxButtons.OK);
}
}
}
现在,在这一点
从我阅读的内容中,我可以做两件事来解决问题。
事物1在我声明之前添加extern" c",以便该名称不会被编译器弄脏。
namespace MyWin32DLL
{
class MyWin32ClassOne
{
public:
extern "C" static __declspec(dllexport) int Getvar();
};
}
当我尝试此操作时,我会从Visual Studio中获得错误,指出"不允许链接规范"。
好,所以我尝试使用dumpbin来查找我功能的名称并使用杂乱的名称作为dllimport呼叫中的入口点。
所以我在dll上运行dumpbin/符号,并且没有函数名称,或其他函数名称。
Dump of file mywin32cppdll.dll
File Type: DLL
Summary
1000 .data
1000 .idata
2000 .rdata
1000 .reloc
1000 .rsrc
4000 .text
10000 .textbss
接下来我尝试dumpbin/entert
Dump of file mywin32cppdll.dll
File Type: DLL
Section contains the following exports for MyWin32CppDll.dll
00000000 characteristics
554CF7D4 time date stamp Fri May 08 13:52:20 2015
0.00 version
1 ordinal base
1 number of functions
1 number of names
ordinal hint RVA name
1 0 00011005 ?Getvar@MyWin32ClassOne@MyWin32DLL@@SAHXZ = @ILT+0(?Getvar@MyWin32ClassOne@MyWin32DLL@@SAHXZ)
Summary
1000 .data
1000 .idata
2000 .rdata
1000 .reloc
1000 .rsrc
4000 .text
10000 .textbss
看着我看不到使用的名称被修补或装饰。但是,作为一个larth,我使用" getVar@mywin32classone@mywin32dll @@ sahxz"作为我的入口点,并且在我的C#程序中仍然遇到相同的错误。
显然我错过了一些东西。如何从C#程序访问DLL函数?
正如您所观察到的那样,名称已被弄乱。您已经设法在被操纵名称的开头省略了?
。您的进口应该是:
[DllImport("MyWin32CppDll.dll", CallingConvention = CallingConvention.Cdecl,
EntryPoint = "?Getvar@MyWin32ClassOne@MyWin32DLL@@SAHXZ")]
public static extern int Getvar();
还请注意,您的功能使用cdecl调用约定。