一般要返回字符串可以用StringBuilder。
下面代码我没有测试,不过你不妨试一下。
[StructLayout(LayoutKind.Sequential)]
public struct PModel
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public StringBuilder Model;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]
public StringBuilder Version;
} [DllImport("TC3XY.dll", CharSet = CharSet.Ansi)]
public static extern int NT_GetModel(long LineID, byte CtrlID, ref PModel rModel);{
PModel model = new PModel();
model.Model = new StringBuilder(10);
model.Version = new StringBuilder(6); NT_GetModel(0, 0, ref model);
}
下面代码我没有测试,不过你不妨试一下。
[StructLayout(LayoutKind.Sequential)]
public struct PModel
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public StringBuilder Model;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]
public StringBuilder Version;
} [DllImport("TC3XY.dll", CharSet = CharSet.Ansi)]
public static extern int NT_GetModel(long LineID, byte CtrlID, ref PModel rModel);{
PModel model = new PModel();
model.Model = new StringBuilder(10);
model.Version = new StringBuilder(6); NT_GetModel(0, 0, ref model);
}
public struct PModel
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public char[] Model;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public char[] Version;
}
[DllImport("TC3XY.dll", CharSet = CharSet.Ansi)]
public static extern int NT_GetModel(ushort LineID, short CtrlID, ref PModel rModel);//
void GetStr(str &st)
{ st.cx=10;
st.cy=11;
}typedef struct str
{
int cx;
int cy;
};c#
[DllImport("t2.dll")]
public static extern void GetStr(ref str x);
str st = new str();
GetStr(ref st);
int x=st.cx;//x=10;
首先谢谢你回答我的问题,我试过拉,有这样的问题:
{"无法封送处理类型为“EkcoTog.PModel”的字段“Model”: 结构字段或类字段的类型不能是 StringBuilder。通常可采用以下方法达到同样的效果,即: 使用一个 String 字段并预先对该字段进行初始化,使其成为一个长度与相应缓冲区的长度相符的字符串。":""}
[DllImport("cplusplus.dll")]
public static extern ECODE GetBinData([MarshalAs(UnmanagedType.LPStr)] StringBuilder pData, [MarshalAs(UnmanagedType.I4)] ref int pnLen);这是可用的代码的一部分,你参考一下吧其中ECODE是C++中的结构体,其他应该能看明白
{
char a;
char b;
char c;
char d;
char e;
char f;
}...............................
class Program
{
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct PModel
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=10)]
public string Model;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]
public string Version;
} [DllImport("TC3XY.dll")]
public extern static void NT_GetModel(int LineID, byte CtrlID, ref PModel pModel); static void Main(string[] args)
{
PModel model = new PModel();
NT_GetModel(0, 0, ref model);
// model.Model == hello
// model.Version == 1.2
}
}// TC3XY.cpptypedef struct _Model
{
char Model[10]; // model
char Version[6]; // version
}TModel, *PModel;extern "C"
{
__declspec(dllexport) int NT_GetModel(unsigned long LineID, BYTE CtrlID, TModel* rModel)
{
strcpy(rModel->Model, "hello");
strcpy(rModel->Version, "1.2");
}
}