Re: [問題] C++ dll傳遞含有char array的struct

看板C_Sharp作者 (Litfal)時間9年前 (2015/06/10 02:16), 編輯推噓0(006)
留言6則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《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

06/10 08:21, , 1F
非常謝謝你的協助 我再試試看這個寫法跟相關的調整
06/10 08:21, 1F

06/10 14:18, , 2F
再請教一下 如果是在C#先new struct是否要用ref才能傳
06/10 14:18, 2F

06/10 14:18, , 3F
遞此struct呢?
06/10 14:18, 3F

06/10 15:35, , 4F
問題解決了 後來我改在C#內先new struct 然後用ref傳遞
06/10 15:35, 4F

06/10 15:36, , 5F
UnmanagedType設成ByValTStr就可以了 雖然還不是很清
06/10 15:36, 5F

06/10 15:36, , 6F
楚這中間的關係 但是還是非常謝謝你的幫忙
06/10 15:36, 6F
文章代碼(AID): #1LTosJov (C_Sharp)
文章代碼(AID): #1LTosJov (C_Sharp)