在Windows平台上,有可能在托管对象周围创建一个COM包装器,该对象可以从非托管代码中使用。
由于我只是在处理一个问题,我想将托管System.IO.Stream引用从托管代码传递给遗留C库函数(它甚至不是Objective),所以我很好奇是否有机会让它工作?
发布于 2013-08-19 10:54:55
不,不能将这样的托管引用传递给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);
// ...
}https://stackoverflow.com/questions/18288940
复制相似问题