如何将浮点数组指针从C ++ / CLI传递给IntPtr到C#
大家好,
我已经将mfc vs6应用程序转换为vs2010。
我的愿望是将托管代码用于非托管c ++应用程序。我在属性页面上激活了CLI扩展功能。
现在来询问我想询问你的输入:
在非托管代码中,我有一个:
Hello Everybody,
I have converted a mfc vs6 application to vs2010.
My wish is to use managed code into a unmanaged c++ application. I have activated on the property page, the CLI extension feature.
Now come the query I would like to ask your inputs about:
In the unmanaged code, I have a:
void UnmanagedFunction()
{
float* pfValues = (float*) malloc(20 * sizeof(float));
pfValues[0..19] = random value.
CNetHelper^ Helper = gcnew CNetHelper();
int iSize = Marshal.SizeOf(typeof(float)) * 20;
IntPtr ptrValues = = Marshal.AllocHGlobal(iSize);
Marshal.Copy(pfValues, 0, ptrValues , 20);
Helper->HelpMethod(ptrValues);
Marshal.FreeHGlobal(ptrValues);
}
in c#
in c#
public class CNetHelper
{
public void HelpMethod(IntPtr ptrValues)
{
// retrieve the samples
// I will mange it via Block.Copy
}
}
The problem:
pfValues cannot be converted from float* to float[]
How should I proceed to copy the float array via pfValues into IntPtr to pass it then to csharp method ?
非常感谢您提前。
祝你好运。
MiQi 。
Thank you very much in advance.
Best regards.
MiQi.
没有理由做这样的代码。在C#端使用float [],在C ++ / CLI中可以直接调用该方法。类似于:
C#side:
There are no reason to do such code as that. On C# side use float[] and in C++/CLI you can call directly that method. Something like:
C# side:
public class CNetHelper
{
public void HelpMethod(float[] values)
{
// You work there as you always do in C#
}
}
C ++ / CLI方面:
C++/CLI side:
void CppCliFunction()
{
cli::array<float> ^values = gcnew cli::array<float>(20);
// Fill array with random values...
for (int i = 0; i != values->Length; ++i)
{
values[i] = random value.
}
CNetHelper^ Helper = gcnew CNetHelper();
Helper->HelpMethod(values);
}
有一个不太明显的解决方案...
在C#程序中,将其添加为另一个帮助方法:
Well there is one not-so-obvious solution...
In the C# program, add this as another "help method":
public unsafe float[] GetFloatArray(float* floats, int count)
{
float[] retVal = new float[count];
for (int i = 0; i < count; i++)
{
retVal[i++] = *floats;
floats++;
}
return retVal;
}
它不明显,因为大多数人都没有意识到.NET很适合使用指针类型就像C ++一样。您必须使用unsafe标志设置编译程序(Properties-> Build->允许不安全的代码,或/或命令行中的/ unsafe)。
现在我还没有尝试过上面的代码所以你可能需要做一些调整,但是概念就在那里,你可以从一个浮点指针和浮点数组的长度。
Its not obvious because most people don't realize that .NET happily works with pointer types just like C++. You will have to compile the program with the "unsafe" flag set (Properties->Build->Allow unsafe code, or /unsafe from the command line).
Now I haven't tried the above code so there may be tweaks you have to do, but the concept is there, you can convert from a floating point pointer and a length to a float array.