C#调用外部vc++ dll ,如何传递引用型字符串数组?

jpyc 2017-12-23 02:13:54
在VC++下定义:

#define DLLEXPORT extern "C" __declspec(dllexport)
extern "C" __declspec(dllexport) int __stdcall StringTest( wchar_t **& str1,wchar_t ** tr2,int iarray);


DLLEXPORT int __stdcall StringTest( wchar_t **& str1,wchar_t ** str2,int iarray)
{
for (int i=0;i<iarray;i++)
{
wcscat(str1[i],str2[i]);
}
return 1;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////



C#下调用:

//外部dll函数申明
[DllImport("csdll.dll", EntryPoint = "StringTest", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
private static extern int StringTest([MarshalAs(UnmanagedType.LPArray)]ref string[] str1, string[] str2, int iarray);


//主函数调用
string[] sParmIds = new String[4];
string[] sParmValues = new String[4];


sParmIds[0] = "炉膛宽度";
sParmIds[1] = "炉膛高度";
sParmIds[2] = "字符串";
sParmIds[3] = "小数";

sParmValues[0] = "4500";
sParmValues[1] = "3500";
sParmValues[2] = "长江黄河";
sParmValues[3] = "3.6";

StringTest(ref sParmIds, sParmValues,4);//在这一步,报错。其他信息: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。
for (int i = 0; i < 3; i++)
MessageBox.Show(sParmIds[i]);

//我的意图是,返回的sParmIds数组为:
//sParmIds[0]=="炉膛宽度4500"
//sParmIds[1]== "炉膛高度3500";
//sParmIds[2]== "字符串长江黄河";
//sParmIds[3]== "小数3.6";

请教诸位,此问题如何解决?
...全文
404 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
xian_wwq 2017-12-25
  • 打赏
  • 举报
回复
个人感觉问题出在wcscat操作上 传入的string类型是定长的,一旦wcscat之后,相当于操作越界了 建议使用stringbuilder来替代string, stringbuilder使用之前要预分配空间。 如果还不行,那不要使用stringbuilder了, 使用IntPtr, 也就是使用指针来操作
jpyc 2017-12-25
  • 打赏
  • 举报
回复
有空的朋友帮忙看下。
jpyc 2017-12-23
  • 打赏
  • 举报
回复
环境是vs2015.

110,476

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧