-1

我需要尽可能干净地将 C# 中的 SlimMath 矩阵作为 FLOAT* 获取到托管 c++ 中。到目前为止,我所有的尝试都是肮脏和破碎的。代码看起来像这样:

C#

Matrix m = Matrix.Identity;
//.......(transform matrix)
//.......Convert it to something I can get into c++ ??
myManagedCPPFunction(m.ToArray());

C++

void myClass::myManagedCPPFunction(?? matTransform)
{
    //FLOAT* f = reinterpret_cast<FLOAT*>(&matTransform); //Cant do this cause managed code
    otherClass->Go((FLOAT*)matTransform);
}

//This is existing code I'm trying to get to:
class otherClass
{
public:
virtual void STDMETHODCALLTYPE Go(const FLOAT *pTransformMatrix);
}

我希望这有足够的意义。

谢谢!

编辑,我忘了提到这已经适用于字符串和常规浮点数,它只是 float[] -> float* 我似乎无法正常工作的东西。

我已经能够让它以这种方式工作,但这并不理想:

unsafe
{
    fixed (float* f = m.ToArray())
        myManagedCPPFunction(f);
}

出于明显的原因,宁愿不这样做。

好的,我想我现在可以使用它(至少它可以编译并运行,但现在我需要进行转换),如下所示:

void myClass::myManagedCPPFunction(SlimDX::Matrix^ matTransform)
{
     FLOAT* f = reinterpret_cast<FLOAT*>(&matTransform);
     otherClass->Go(f);
}
4

2 回答 2

1

这就是您如何在 C++ 中声明它以供 C# 使用(请参阅p/invoke教程):

extern "C" {
    __declspec( dllexport ) void STDMETHODCALLTYPE Go(float* pMatrix);

    void Go(float* pMatrix) {
       // do your stuff here. assume the matrix has 16 elements
    }
}

在 C# 中:

[DllImport("myDll.dll")]
public static extern void Go(float[] matrix);

示例 C# 代码:

Matrix m = myMatrix;
Go(m.ToArray());

编辑:如果您使用 C++/CLI 托管程序集,那么您可以像这样声明函数:

using namespace System;

public ref class Class1
{
    public:

        void Go(array<float> ^ pFloat)
        {
            ... 
        }
    };
于 2013-01-09T17:45:02.763 回答
0

如果它是托管 C++,您可以使用与 C# 中相同的类型。为什么不像这样声明 C++ 方法:

void myClass::myManagedCPPFunction(Matrix^ matTransform)
于 2013-01-09T22:32:54.213 回答