1

これを機能させることは可能ですか?

template<class T>
fun(T * t) { t->someMemberFunc(); }

...コードのどこかに:

ManagedType ^ managedP = gcnew ManagedType();
UnmanagedType * unmanagedP = new UnmanagedType();
fun(managedP);
4

2 に答える 2

1

管理対象オブジェクトのアドレスを取得することはできません。ガベージ コレクターは、ポインター値をいつでも無効にして、メモリ内で移動できます。少なくとも、最初にオブジェクトを固定する必要があります。私が有効な構文を思い付くことができないという短所は、メソッド呼び出しを行うためだけにピン留めすることは望ましくありません。引数をトラッキング ハンドルとして宣言する必要があります。

template<typename T>
void fun(T^ t) { t->method(); }
于 2009-11-26T16:54:31.917 に答える
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
于 2009-12-08T13:55:02.350 に答える