2009-11-26 96 views

回答

1

你不能把一個管理對象的地址。垃圾收集器可以在內存中移動它,隨時使指針值無效。至少你必須先固定物體。對我而言,由於無法提供有效的語法,因此僅僅爲了進行方法調用就不可取。你需要聲明參數作爲跟蹤處理:

template<typename T> 
void fun(T^ t) { t->method(); } 
1

這可能是無關的問題,但和的GCHandle可以gcroot是有用的;他們允許你獲得一個非託管對象封裝句柄到一個被管理對象:

// hold_object_reference.cpp 
// compile with: /clr 
#include "gcroot.h" 
using namespace System; 

#pragma managed 
class StringWrapper { 

private: 
    gcroot<String^> x; 

public: 
    StringWrapper() { 
     String^str = gcnew String("ManagedString"); 
     x = str; 
    } 

    void PrintString() { 
     String^targetStr = x; 
     Console::WriteLine("StringWrapper::x == {0}", targetStr); 
    } 
}; 
#pragma unmanaged 
int main() { 
    StringWrapper s; 
    s.PrintString(); 
} 

----------------- 

Imports System 
Imports System.IO 
Imports System.Threading 
Imports System.Windows.Forms 
Imports System.Runtime.InteropServices 
Imports System.Security.Permissions 

Public Delegate Function CallBack(ByVal handle As Integer, ByVal param As IntPtr) As Boolean 

Module LibWrap 

    ' passing managed object as LPARAM 
    ' BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam); 
    <DllImport("user32.dll")> _ 
    Function EnumWindows(ByVal cb As CallBack, ByVal param As IntPtr) As Boolean 
    End Function 
End Module 'LibWrap 


Module App 

    Sub Main() 
     Run() 
    End Sub 

    <SecurityPermission(SecurityAction.Demand, UnmanagedCode:=true)> _ 
    Sub Run() 

     Dim tw As TextWriter = System.Console.Out 
     Dim gch As GCHandle = GCHandle.Alloc(tw) 

     Dim cewp As CallBack 
     cewp = AddressOf CaptureEnumWindowsProc 

     ' platform invoke will prevent delegate to be garbage collected 
     ' before call ends 
     LibWrap.EnumWindows(cewp, GCHandle.ToIntPtr(gch)) 
     gch.Free() 

    End Sub 


    Function CaptureEnumWindowsProc(ByVal handle As Integer, ByVal param As IntPtr) As Boolean 
     Dim gch As GCHandle = GCHandle.FromIntPtr(param) 
     Dim tw As TextWriter = CType(gch.Target, TextWriter) 
     tw.WriteLine(handle) 
     Return True 

    End Function 
End Module 
相關問題