在Windows平台上,可以围绕可能从非托管代码使用的托管对象创建COM包装。
由于我只是处理一个问题,我想将托管的System.IO.Stream引用从托管代码传递给遗留的C库函数(它甚至不是Objective-C),我很好奇是否有有机会让这个工作吗?
答案 0 :(得分:3)
不,您无法将此类托管引用传递给iOS中的C代码。
但你可以进行反向P / Invoke调用:你给本机代码一个委托,你可以从C调用该委托作为函数指针。
以下是一些(未经测试的)示例代码,可以让您走上正确的轨道:
delegate long GetLengthCallback (IntPtr handle);
// Xamarin.iOS needs to the MonoPInvokeCallback attribute
// so that the AOT compiler can emit a method
// that can be called directly from native code.
[MonoPInvokeCallback (typeof (GetLengthCallback)]
static long GetLengthFromStream (IntPtr handle)
{
var stream = (Stream) GCHandle.FromIntPtr (handle).Target;
return stream.Length;
}
static List<object> delegates = new List<object> ();
static void SetCallbacks (Stream stream)
{
NativeMethods.SetStreamObject (new GCHandle (stream).ToIntPtr ());
var delGetLength = new GetLengthCallback (GetLengthFromStream);
// This is required so that the GC doesn't free the delegate
delegates.Add (delGetLength);
NativeMethods.SetStreamGetLengthCallback (delGetLength);
// ...
}