用多个指针在C#中封送本机.dll
使用C++编写以下代码:用多个指针在C#中封送本机.dll,c#,pinvoke,marshalling,mixed-mode,C#,Pinvoke,Marshalling,Mixed Mode,使用C++编写以下代码: NCOID是连接标识符 pParName参数名 pSubName子参数名称(如果有) pValue\u out指向长度为FCL\u PAR\u VALUE\u LENGH的字符数组的指针 nValue size pValue_out向量的实际大小(至少FCL_PAR_VALUE_LENGH) 我的尝试是: [DllImport("mydll.dll", CharSet = CharSet.Ansi,CallingConvention=CallingConventio
- NCOID是连接标识符
- pParName参数名
- pSubName子参数名称(如果有)
- pValue\u out指向长度为FCL\u PAR\u VALUE\u LENGH的字符数组的指针
- nValue size pValue_out向量的实际大小(至少FCL_PAR_VALUE_LENGH)
[DllImport("mydll.dll", CharSet = CharSet.Ansi,CallingConvention=CallingConvention.Cdecl)]
public static extern int ReadParameter(ConnectionId_T pConId, IntPtr pParName,
ref IntPtr pSubName, ref IntPtr[] pValue_out, int nValueSize);
我使用以下代码调用该函数:
# nConId is returned from another function and the his value is 0
public const int FCL_PAR_VALUE_LENGH = 128;
string param_string = "AUXF";
IntPtr pParName = (IntPtr)Marshal.StringToHGlobalAnsi(param_string);
string subparam_string = "T";
IntPtr pSubName = (IntPtr)Marshal.StringToHGlobalAnsi(subparam_string);
IntPtr[] aParValue = new IntPtr[FCL_PAR_VALUE_LENGH];
int returnedValue = ReadParameter(nConId, pParName, ref pSubName,
ref aParValue, FCL_PAR_VALUE_LENGH);
当我运行代码时,我得到一个AccessViolationException,因此我猜我的调用中有问题
我的马歇尔错了吗?为了获得良好的响应,我需要在代码中做哪些更改
PS:我也知道这个调用也会返回一些东西到
aParValue
你对那些char*
s太过努力了。将System.String
封送用于输入,将StringBuilder
封送用于输出是完全合法的(并受到鼓励)
[DllImport("mydll.dll", CharSet = CharSet.Ansi,CallingConvention=CallingConvention.Cdecl)]
public static extern int ReadParameter(
ConnectionId_T pConId,
string pParName,
string pSubName,
StringBuilder pValue_out,
int nValueSize);
用法
您没有给出任何关于连接id\u t
的基本类型的指示,因此我假设您已经排除了这一问题
工作起来很有魅力!非常感谢:)
[DllImport("mydll.dll", CharSet = CharSet.Ansi,CallingConvention=CallingConvention.Cdecl)]
public static extern int ReadParameter(
ConnectionId_T pConId,
string pParName,
string pSubName,
StringBuilder pValue_out,
int nValueSize);
const int sbLength = 256; //use a domain relevant value
StringBuilder sb = new StringBuilder(sbLength + 1); //for null character, hard to say if you need it without seeing the C++ code, but easier to just add it than find out.
int result = ReadParameter(conId, "paramname", "paramsubname", sb, sbLength);