我有一个C ++应用程序,应该使用DLL中的某些函数,这些函数是用C#编写的,并使用mono编译。我已经想出如何使用我的C ++代码运行这些C#函数,但仍然无法理解如何引用通常是已知大小的数组的C#结果。
我的C ++代码如下所示:
MonoDomain* domain = mono_jit_init("CSharpDLLname.dll");
MonoAssembly* assembly = mono_domain_assembly_open(domain, "CSharpDLLname.dll");
MonoImage* image = mono_assembly_get_image(assembly);
MonoClass* klass = mono_class_from_name(image, "MyNamespace", "MyClass");
MonoObject* object = mono_object_new(domain, klass);
// call ctor
mono_runtime_object_init(object);
MonoMethodDesc* mdesc = mono_method_desc_new(":test(single[])", false);
MonoMethod* method = mono_method_desc_search_in_class(mdesc, klass);
void* args[1];
args[0] = &something;
// call function with provided args
mono_runtime_invoke(method, object, args, NULL);
// shutdown the runtime
mono_jit_cleanup (domain);
这是我在C#DLL中调用的函数类型:
public static float[] tester(float[] arr)
{
// ... do things to arr
// create an array of known size
float[] barr = new float[3];
barr[0] = 1;
barr[1] = 2;
barr[2] = 3;
// return it as result
return barr;
}
问题是如何从我的C ++代码中获取barr
的指针或副本?
我尝试使用
MonoObject* returnObj = mono_runtime_invoke(method, object, args, NULL);
float* result = (float*)mono_object_unbox (returnObj);
但结果是
object.c:6493处的断言,条件`obj-> vtable-> klass-> valuetype'未满足。 ... 执行本机代码时获得SIGABRT。这通常表明 单声道运行时或其中一个本机库中的致命错误 由您的应用程序使用。
如果我返回单个值public static float tester()
,那么它可以工作,我可以读取结果。现在我希望能够读取一个数组。
返回数组的C#函数的简单C +用法示例会很棒。或者,如果mono_runtime_invoke()
和mono_object_unbox()
不是正确的方法(我是C#和单声道的初学者),很高兴知道如何正确地做到这一点 - 再次,基本的例子是值得赞赏的。
答案 0 :(得分:0)
我找不到关于如何返回或复制整个数组的答案,但却想出了另一种方法。由于获取blittable类型的工作,而不是返回整个数组的函数,我曾经得到数组的每个元素。例如:
C#代码:
private float[] m_array; // the array we want to copy to our C++ code
private int m_numElements; // length of the array
public static int getLength()
{
return m_numElements;
}
public static float[] getArray() // this will not work
{
return m_array;
}
public static float getArrayElement(int index) // we will use this instead!
{
return m_array[index];
}
C ++代码中的用法:
MonoObject* lengthObj = mono_runtime_invoke(methodGetLength, object, NULL, NULL);
int length = *(int*)mono_object_unbox(lengthObj);
// now allocate the array where you will cope the result to
std::vector<float> array; // or could also be float[length]
array.resize(length);
for (int i=0; i<length; ++i){
void* args[1];
args[0] = &i;
// obtain the next element with index i
MonoObject* elementObj = mono_runtime_invoke(methodGetElement, object, args, NULL);
// copy the result to our array
array[i] = *(float*)mono_object_unbox(elementObj);
}