作者Litfal (Litfal)
看板C_Sharp
標題Re: [問題] C++ dll傳遞含有char array的struct
時間Wed Jun 10 02:16:49 2015
※ 引述《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)
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.135.179.10
※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1433873811.A.CB9.html
→ petercoin: 非常謝謝你的協助 我再試試看這個寫法跟相關的調整 06/10 08:21
→ petercoin: 再請教一下 如果是在C#先new struct是否要用ref才能傳 06/10 14:18
→ petercoin: 遞此struct呢? 06/10 14:18
→ petercoin: 問題解決了 後來我改在C#內先new struct 然後用ref傳遞 06/10 15:35
→ petercoin: UnmanagedType設成ByValTStr就可以了 雖然還不是很清 06/10 15:36
→ petercoin: 楚這中間的關係 但是還是非常謝謝你的幫忙 06/10 15:36