我目前正在探索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