楼主:
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)