[英]How to convert the returned interface variable by a method to object?
我在c ++库中使用ac#包装程序,被调用函数返回指向类对象的指针。 在c#包装器中,如果我调用该方法,它将返回一个接口变量。 该接口变量为null,因此无法获取值。 我应该如何处理该接口变量以获得值。 有人请帮助我。
在下面的代码中,我们有ROOTNET.Interface.NTH1F它是一个接口,其中ROOTNET.NTH1F是一个类
using ROOTNET.Utility;
using ROOTNET.Interface;
NTH1F g = new ROOTNET.NTH1F("g", "background removal", doubleArrayX.Length - 1,
doubleArrayX);
g.SetContent(doubleArrayY);
g.GetXaxis().SetRange(xmin, xmax);
ROOTNET.NTH1F bkg = new ROOTNET.NTH1F(g);
bkg.Reset();
bkg.Add(g.ShowBackground(80, ""));
在上面的即时消息中,我期望背景去除值以bkg保存,但是bkg包含所有零,请您帮我将g的背景去除值转换为bkg。
其中ShowBackground(int niter, string option)
方法的代码是
public unsafe virtual NTH1 ShowBackground (int niter, string option)
{
NetStringToConstCPP netStringToConstCPP = null;
NetStringToConstCPP netStringToConstCPP2 = new NetStringToConstCPP (option);
NTH1 bestObject;
try
{
netStringToConstCPP = netStringToConstCPP2;
int num = *(int*)this._instance + 912;
bestObject = ROOTObjectServices.GetBestObject<NTH1> (calli ((), this._instance, niter, netStringToConstCPP.op_Implicit (), *num));
}
catch
{
((IDisposable)netStringToConstCPP).Dispose ();
throw;
}
((IDisposable)netStringToConstCPP).Dispose ();
return bestObject;
}
您不能将C ++返回的指针值视为接口(我猜除非是COM接口)。 C ++和C#类和接口可能(而且大多数情况下确实)具有不同的低级结构,因此您不能简单地将它们强制转换为另一种。
唯一的方法是为您的库返回的C ++类编写另一个包装。 它看起来应该更像这样:
C ++ / DLL:
__declspec(dllexport) void * ReturnInstance()
{
return new MyClass();
}
__declspec(dllexport) void MyClass_CallMethod(MyClass * instance)
{
instance->Method();
}
C#:
[DllImport("MyDll.dll")]
private static extern IntPtr ReturnInstance();
class MyClassWrapper
{
private IntPtr instance;
[DllImport("MyDll.dll")]
private static extern void MyClass_CallMethod(IntPtr instance);
public MyClassWrapper(IntPtr newInstance)
{
instance = newInstance;
}
public void Method()
{
MyClass_CallMethod(instance);
}
}
// (...)
IntPtr myClassInstance = ReturnInstance();
MyClassWrapper wrapper = new MyClassWrapper(myClassInstance);
wrapper.Method();
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.