将带有嵌入字符串的结构传递给C dll时,C#P/Invoke不起作用
我有一个旧的C dll,需要用C代码包装。我使用P/Invoke签名工具包获得以下结构定义:将带有嵌入字符串的结构传递给C dll时,C#P/Invoke不起作用,c#,pinvoke,C#,Pinvoke,我有一个旧的C dll,需要用C代码包装。我使用P/Invoke签名工具包获得以下结构定义: [StructLayout(LayoutKind.Sequential)] internal struct SDRMSG { public uint Stream; public uint Function; public uint Wbit; public int Length; [MarshalA
[StructLayout(LayoutKind.Sequential)]
internal struct SDRMSG
{
public uint Stream;
public uint Function;
public uint Wbit;
public int Length;
[MarshalAsAttribute(UnmanagedType.LPStr)]
public string Buffer;
public int Error;
public int Next;
[MarshalAsAttribute(UnmanagedType.LPStr)]
public string Txtp;
public int Txtc;
[MarshalAsAttribute(UnmanagedType.LPStr)]
public string Wtxtp;
public int Wtxtc;
}
typedef struct {
unsigned int stream;
unsigned int function;
unsigned int wbit;
SDRLENGTH length;
unsigned char * buffer;
SDRLENGTH error;
int next;
unsigned char * txtp;
SDRLENGTH txtc;
unsigned char * wtxtp;
SDRLENGTH wtxtc;
} SDRMSG;
根据原始的C定义:
[StructLayout(LayoutKind.Sequential)]
internal struct SDRMSG
{
public uint Stream;
public uint Function;
public uint Wbit;
public int Length;
[MarshalAsAttribute(UnmanagedType.LPStr)]
public string Buffer;
public int Error;
public int Next;
[MarshalAsAttribute(UnmanagedType.LPStr)]
public string Txtp;
public int Txtc;
[MarshalAsAttribute(UnmanagedType.LPStr)]
public string Wtxtp;
public int Wtxtc;
}
typedef struct {
unsigned int stream;
unsigned int function;
unsigned int wbit;
SDRLENGTH length;
unsigned char * buffer;
SDRLENGTH error;
int next;
unsigned char * txtp;
SDRLENGTH txtc;
unsigned char * wtxtp;
SDRLENGTH wtxtc;
} SDRMSG;
发生的事情是我需要初始化这个结构并将它发送到一个C.dll,在那里.dll将用数据填充缓冲区字段。原始C结构中的缓冲区字段只是指向我在客户机代码中初始化的字符数组的指针。有了指针,C.dll就可以直接写入缓冲区。我试图用C#代码得到相同的结果,但无论我怎么做,我似乎都无法正确初始化缓冲区字段,以便C.dll可以用数据填充它。我的客户机代码总是空的。这里有一个尝试(在我不太记得的几个尝试中)似乎不起作用
secsMessage.Stream = 1;
secsMessage.Function = 13;
secsMessage.Wbit = 1;
secsMessage.Length = 8000;
secsMessage.Buffer = new string('\0', 8000);
有人能帮我找出如何初始化结构,以便C.dll可以写入缓冲区吗?示例应该为您找到正确的路径。听起来您希望将
字节[]
作为某些结构成员的托管类型,而不是字符串。如果数据表示C中以null结尾的char
数组,则需要string
。如果它是一个确定大小的缓冲区,其中将填充可能包含嵌入零的数据,那么您将需要一个字节[]
。缓冲区的大小不是确定的。我在这里硬编码到一个特定的大小只是为了简单。我认为字符串是正确的类型。我实际上找到了该链接,并尝试按照提供的示例进行操作。还是不行。当我在C++中写同样的代码传递给缓冲区的指针时,一切都会正常工作。似乎不管我如何使用C代码,缓冲区都是空的。我想我可能不得不求助于我的C#应用程序中的非托管代码,然后重新使用指针。不过,我也不知道该怎么做,所以需要做一些阅读。