c# c++混编参数传递

asd_yt 2017-08-22 09:27:10
C++ Code
typedef struct _result_array
{
int num;
int nums;
char *path;
string name[100];

}*result_array;

int _stdcall test01(char *guest_img_path, result_array p)
{
string path1 = guest_img_path;
p->num = 1;
p->nums = 2;
p->path = guest_img_path;
return 0;
}

C# code
namespace CSharpCallDLL
{
[StructLayout(LayoutKind.Sequential,CharSet = CharSet.Unicode, Pack = 1)]
public struct result_array
{
public int num;
public int nums;

[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 50)]
public string path;

[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 50)]
public string[] name;
}
class Program
{
[DllImport(@"C:\Users\meng\Desktop\csharp\fasterrcnn\x64\Release\CreateDLL.dll", EntryPoint = "test01", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
public static extern int test01(string guest_img_path, ref result_array p);

public static void Main(string[] args)
{
string guest_imgpath = "C:\\Users\\file";
result_array p = new result_array();
p.num = 0;
p.nums = 0;
p.path = " ";
string guest_imgpath = "C:\\Users\\meng\\Desktop\\file";
int r = test01(guest_imgpath,ref p);
Console.ReadKey();
}
}
}
结构体成员可以从c#中传递到c++DLL,在DLL中修改结构体成员的值后,在C#中结构体p的成员整形p.num和p.nums的值改变,而字符串p.path则没变或乱码,求大神赐教!
...全文
270 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
xian_wwq 2017-08-22
  • 打赏
  • 举报
回复
2楼说的有理,P/Invoke的时候,采用c的基本类型问题会少很多
白衣如花 2017-08-22
  • 打赏
  • 举报
回复
char*在结构体中只有4个字节。C#对应是IntPtr 或者用char[] 指定长度
homesos 2017-08-22
  • 打赏
  • 举报
回复
string name[100]; 也别用string,用简单数据类型,也用char数组
homesos 2017-08-22
  • 打赏
  • 举报
回复
不能用char *,用char数组。
asd_yt 2017-08-22
  • 打赏
  • 举报
回复
引用 1 楼 homesos 的回复:
不能用char *,用char数组。
已解决,谢谢
asd_yt 2017-08-22
  • 打赏
  • 举报
回复
引用 1 楼 homesos 的回复:
不能用char *,用char数组。
我需要传递字符串,这样的话在C++DLL中怎么赋值呢,如果传递字符串数组的话,char数组是不是没法传递了?

110,539

社区成员

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

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

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