我目前正在探索C#中的DLL导出函数和P /调用。 我创建非常简单的.dll文件:从DLL调用方法时C#应用程序块
Test.h
#ifndef TEST_DLL_H
#define TEST_DLL_H
extern "C" __declspec(dllexport) const char * __cdecl hello();
extern "C" __declspec(dllexport) const char * __cdecl test();
#endif // TEST_DLL_H
Test.cpp的
#include <stdlib.h>
#include "test.h"
#include <string.h>
const char* hello()
{
char *novi = (char *)malloc(51);
strcpy(novi, "Test.");
return novi;
}
const char * test()
{
return "Test.";
}
我编译它,并在C#项目中使用这样的:
[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr hello();
[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern string test();
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(test());
IntPtr a = hello();
MessageBox.Show(Marshal.PtrToStringAnsi(a));
}
但它不工作。 test()
成功调用并返回正确的字符串。但hello()
只是挂起程序。如果我从hello()
定义中除去malloc行并返回常量,那么一切正常,所以我想现在我知道malloc存在一个问题。
此外,我已经看到,当返回类型是char *时不应该使用字符串。如果这是真的,为什么我们应该使用IntPtr?
您是否尝试过调试它?为此,在C#项目属性Debug页面中,可以启用非托管代码调试。然后在C#项目中打开test.cpp,在hello中放置一个断点并从visual studio启动C#项目。 – 2012-07-09 10:39:34