簡體   English   中英

c#interop編組和處理

[英]c# interop marshalling and disposing

我有一個用C ++設計的DLL,包含在一個C#項目中,我有一些奇怪的AccessViolationExceptions不合理地發生。 我懷疑我的垃圾沒有正確收集。 我有一個非托管方法apiGetSettings(來自DLL),它應該將數據復制到一個Settings對象(實際上是原始代碼中的一個struct,但.NET InterOp只允許將數據作為類對象導入。我使用System.Runtime.InteropServices。分配和釋放內存的Marshal方法,但它可能會留下垃圾,使一切崩潰。

現在,我應該在Settings類中實現IDisposable方法(它是不受管理的嗎?)。 如果是這樣,我如何處理作為UnmanagedType.ByValTStr編組的字符串以及如何處理Settings對象?

using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
class Settings
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 33)]
internal string d;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]
internal string t;
internal int b;
}

[DllImport(".\\foobar.dll", EntryPoint = "getSettings")]
private static extern int apiGetSettings(IntPtr pointerToSettings);

void GetSettings(ref Settings settings)
{
int debug = 0;

// Initialize a pointer for the structure and allocate memory
IntPtr pointerToSettings = Marshal.AllocHGlobal(43);

// Connect the pointer to the structure
Marshal.StructureToPtr(settings, pointerToSettings, true);

// Point the pointer
debug = apiGetSettings(pointerToSettings);

// Copy the pointed data to the structure
Marshal.PtrToStructure(pointerToSettings, settings);

// Free the allocated memory
Marshal.FreeHGlobal(pointerToSettings);
}

不,您不需要實現IDisposable。 您的Settings類是一個托管類(這些屬性僅用於運行時),並且將被垃圾回收。

我的第一個猜測:你正在分配43個字節,但你的兩個字符串加起來超過70個字節(記住,除非你在古老的Win98 / Me上,一個字符的大小是2個字節),所以你沒有分配足夠。 使用Marshal.SizeOf代替動態確定結構的大小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM