Re: [问题] C++ dll传递含有char array的struct

楼主: Litfal (Litfal)   2015-06-10 02:16:49
※ 引述《petercoin (彼得币)》之铭言:
: 我手上有一个C++写的dll
: 现在在C#写的程式内使用这个dll
: 在这个dll内有一个struct
: typedef struct _A
: {
: WCHAR buf[64];
: DWORD index;
: } A;
: 会被当成function的参数传递
: int funA(A *a)
: {
: a.buf...;
: index = ...;
: }
: 现在我想在C#内叫用funA
: [DllImport("Mydll.dll", CallingConvention = CallingConvention.StdCall, CharSet
: = CharSet.Unicode)]
: public static extern int funA(IntPtr a);
: 有先确认过dll确实有值在buf里面
: 但是不管怎样都没有办法得到buf的内容
: 在猜想会不会是memory没有正确传递?
: 想请教一下该如何才能正确将dll传的值抓出来呢?
using System.Runtime.InteropServices;
// 让编译后的成员顺序依照指定顺序排序
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)]
public struct A
{
// 因为是接收且由C alloc,直接宣告这样;如果是传递写法会有些不同
// 这边写法蛮多、是最需要尝试的部分
[MarshalAsAttribute(UnmanagedType.LPWStr)]
public string buf;
public uint index;
}
// 宣告部分直接改成out参考,这里它类似于指标的用途
// 也可以用Intptr后Marshal.PtrToStructure去转,但如果可以,指定类型会更方便
// 如果遇到问题可以改回IntPtr,把address print出来,看看是否正确
[DllImport("Mydll.dll", CallingConvention = CallingConvention.StdCall, CharSe
= CharSet.Unicode)]
public static extern int funA(out A a);
不保证可以work,有时需要经过一些尝试,但主要是调整资料型别与属性(attribute)
作者: petercoin (彼得币)   2015-06-10 08:21:00
非常谢谢你的协助 我再试试看这个写法跟相关的调整再请教一下 如果是在C#先new struct是否要用ref才能传递此struct呢?问题解决了 后来我改在C#内先new struct 然后用ref传递UnmanagedType设成ByValTStr就可以了 虽然还不是很清楚这中间的关系 但是还是非常谢谢你的帮忙

Links booklink

Contact Us: admin [ a t ] ucptt.com