我有一个包含两个函数的c++ dll
const char* getVersionText1(void);
void getVersionText2(const char** res);
这两个函数都返回描述产品版本的字符串。第一个函数将其作为const char*返回(意味着在内部分配和释放),而第二个函数获取char*指针并将其设置为指向描述版本的char*。
我想从C#中调用这些函数并显示文本。 我不能使用[dllimport ...]样式,因为调用函数的顺序很重要。我先调用构造函数,然后是getVersion,最后是析构函数。所以必须首先将dll加载到内存中。
请您提供打印这两个函数文本的几行代码。 我是C#的新手,请原谅如果您发现我的代码有问题 我尝试过
static class NativeMethods{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
}
class Program{
// Define function pointers to entires in DLL
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr getVersionText1();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void getVersionText2(IntPtr );
static void Main(string[] args){
// Pointers to functions of DLL.
getVersionText1 f1;
getVersionText2 f2;
IntPtr pDll = NativeMethods.LoadLibrary("p:\\my.dll");
IntPtr pAddressOfFunctionToCall;
pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "getVersionText1 ");
f1 = (getVersionText1)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(getVersionText1));
pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "getVersionText2 ");
f2 = (getVersionText2)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(getVersionText2));
// Here I don't know what to do. It doesn't work ????
IntPtr verText = f1();
String s = Marshal.PtrToStringAuto(verText);
Console.WriteLine(s); // Doesnt work
// And how to use the second function. How do I sent a pointer to char* ???
}
}
getVersionText1
和getVersionText2
是实际的导出函数名称吗?C++名称重整通常会更改您的导出名称。您可以使用任何DLL导出查看器检查导出的名称。 - Panda Pajama