编组float数组到C# [英] Marshalling float Array to c#
本文介绍了编组float数组到C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图封送包含一个C浮子阵列++ DLL到C#中的结构
I'm trying to marshal a struct that contains a float-Array from a C++ DLL to C#.
我创建从下面的代码的C ++ DLL:
I created the C++ DLL from the following code:
//MarshalTest.h
namespace mTest{
typedef struct {
float data[3];
int otherStuff;
} dataStruct;
extern "C" __declspec(dllexport) dataStruct getData();
}
//MarshalTest.cpp
#include "MarshallTest.h"
using namespace std;
namespace mTest{
dataStruct getData(){
dataStruct d = {{ 16, 2, 77 }, 5};
return d;
}
}
我用下面的代码,以使的getData - 功能在C#中可用:
I use the following code to make the getData-Function available in C#:
public unsafe struct dataStruct{
public fixed byte data[3];
public int otherStuff;
public unsafe float[] Data{
get{
fixed (byte* ptr = data){
IntPtr ptr2 = (IntPtr)ptr;
float[] array = new float[3];
Marshal.Copy(ptr2, array, 0, 3);
return array;
}
}
set{
fixed (byte* ptr = data){
//not needed
}
}
}
}
[DllImport("MarshallTest", CallingConvention = CallingConvention.Cdecl)]
private static extern dataStruct getData ();
在打印数据[]在C#中我得到以下的输出:
1.175494E-38
1.610935E-32
8.255635E-20
When printing data[] in C# I get the following output: 1.175494E-38 1.610935E-32 8.255635E-20
我在做什么错了?
推荐答案
您必须使用正确的类型:
You must use the right type:
public unsafe struct dataStruct2
{
public fixed float data[3];
public int otherStuff;
public unsafe float[] Data
{
get
{
fixed (float* ptr = data)
{
float[] array = new float[3];
Marshal.Copy((IntPtr)ptr, array, 0, 3);
return array;
}
}
}
}
请注意对于一小阵,你甚至可以用:
Note that for a small array, you can even use:
public struct dataStruct
{
public float data1;
public float data2;
public float data3;
public int otherStuff;
public float[] Data
{
get
{
return new[] { data1, data2, data3 };
}
}
}
不使用不安全的代码。
without using unsafe code.
这篇关于编组float数组到C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文