问题描述
我有如下因素非托管结构。
I have the folowing unmanaged structure.
struct MyNativeStruct_Foo
{
char product_name[4];
char product_model[2];
}
和托管相当于
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MyManagedStruct_Foo
{
[MarshalAs(UnmanagedType.LPStr, SizeConst = 4)]
public string product_name;
[MarshalAs(UnmanagedType.LPStr, SizeConst = 2)]
public string product_model;
}
不幸的是,蜇伤不是空终止。正在使用的所有4个字符的产品名称。如果我定义与LPSTR的管理结构中的字符串必须终止0
Unfortunately the stings are not null terminated. All 4 characters for the product name are used. If I define the managed structure with "LPStr" the string have to be 0 terminated.
有另一种方式来定义管理结构?能够定义自定义的Marshaller属性? ?或者你有其他的想法。
Is there another way to define the managed structure? It is possible to define a custom Marshaller attribute? Or do you have other Ideas?
请注意;
中的天然结构不能改变。
Note;The native structure can not be changed.
由于
安伯格
改变为LPSTR(评论贾森Larke)
changed to LPStr (comment Jason Larke)
推荐答案
您可以改变你的编组对待字符串的字节
个固定大小的数组,然后使用编码
类字节转换为托管字符串。
You can change your marshalling to treat the string as a fixed-size array of bytes
s and then using the Encoding
class to convert the bytes into a managed string.
即
[StructLayout(LayoutKind.Sequential)]
public struct MyManagedStruct_Foo
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=4)]
public byte[] product_name;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=2)]
public byte[] product_model;
public string GetProductName()
{
return System.Text.Encoding.ASCII.GetString(this.product_name);
}
public string GetProductModel()
{
return System.Text.Encoding.ASCII.GetString(this.product_model);
}
}
不完全是世界上最性感的结构,但它应罚款为您的需求。
Not exactly the sexiest struct in the world, but it should be fine for your needs.
这篇关于元帅不是0结尾的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!