写了两个函数接口, 一个返回int, 另一个返回const char *字符串
dll方法返回const char * 时, c# 程序使用IntPtr类型声明, 不然会乱码
Qt dll 接口函数定义:
main.cpp
extern "C" __declspec(dllexport) int add(int numberA, int numberB)
{
return numberA + numberB;
}
extern "C" _declspec(dllexport) const char *sayHi()
{
//这里可以定义中文
const char * s = "Hi";
return s;
}
C#调用
[DllImport("qtdialog.dll", EntryPoint = "add", CallingConvention = CallingConvention.Cdecl)]
public static extern int add(int numberA, int numberB);
[DllImport("dll.dll", EntryPoint = "sayHi", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr sayHi();
private void buttonAdd_Click(object sender, RoutedEventArgs e)
{
int getAddValue = add(1, 2);
// 接收到的字符串需要转成ASCII
IntPtr temp = sayHi();
string str = Marshal.PtrToStringAnsi(temp).Trim();
}