在C#中,如何调用DLL函数,该函数返回包含字符串指针的非托管结构? [英] In C#, how do I invoke a DLL function that returns an unmanaged structure containing a string pointer?
问题描述
我得到了一个DLL("InfoLookup.dll"),该DLL在内部分配结构并从查找函数返回指向它们的指针.这些结构包含字符串指针:
I have been given a DLL ("InfoLookup.dll") that internally allocates structures and returns pointers to them from a lookup function. The structures contain string pointers:
extern "C"
{
struct Info
{
int id;
char* szName;
};
Info* LookupInfo( int id );
}
在C#中,如何声明结构布局,声明Interop调用以及(假设返回了非null值)如何利用字符串值?换句话说,如何将以下内容转换为C#?
In C#, how can I declare the structure layout, declare the Interop call, and (assuming a non-null value is returned) utilize the string value? In other words, how do I translate the following into C#?
#include "InfoLookup.h"
void foo()
{
Info* info = LookupInfo( 0 );
if( info != 0 && info->szName != 0 )
DoSomethingWith( info->szName );
// NOTE: no cleanup here, the DLL is caching the lookup table internally
}
推荐答案
尝试以下布局.使用 PInvoke Interop Assistant 自动生成的代码.手工编码的LookpInfoWrapper()
Try the following layout. Code automatically generated using the PInvoke Interop Assistant. Hand coded LookpInfoWrapper()
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct Info {
/// int
public int id;
/// char*
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)]
public string szName;
}
public partial class NativeMethods {
/// Return Type: Info*
///id: int
[System.Runtime.InteropServices.DllImportAttribute("InfoLookup.dll", EntryPoint="LookupInfo")]
public static extern System.IntPtr LookupInfo(int id) ;
public static LoopInfoWrapper(int id) {
IntPtr ptr = LookupInfo(id);
return (Info)(Marshal.PtrToStructure(ptr, typeof(Info));
}
}
这篇关于在C#中,如何调用DLL函数,该函数返回包含字符串指针的非托管结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!