如何通过引用将托管数组传递给非托管库?
我正在创建一个托管 C++/CLI DLL,它包装并提供驻留在 C++ 静态库中的单个函数。
除了一个一直困扰我的问题之外,我大部分工作都完成了。
以下是该函数在我的非托管库的 .h 文件中的样子。
typedef struct
{
float a;
float b;
}MyStruct;
bool GetData(float p1, float* p2, MyStruct buffer[]);
以下是到目前为止我对 C++/CLI 包装器的了解:
H 文件:
using namespace System::Runtime::InteropServices
public ref struct MyManagedStruct
{
float a;
float b;
}
public ref class Wrapper
{
bool static GetDataManaged(
float p1, [Out] float %p2,
array<MyManagedStruct^> ^ managedBuffer);
}
CPP 文件:
bool Wrapper::GetDataManaged(
float p1, [Out] float %p2,
array<MyManagedStruct^> ^ managedBuffer)
{
float f;
//managed buffer is assumed allocated by the .net caller
MyStruct* unmanagedBuffer = new MyStruct[managedBuffer->Length];
bool retval = GetData(p1, &f, unmanagedBuffer);
/* this doesn't work... any better suggestions?
for (int i=0;i<n;i++)
BallDatabuffer[i] = buffer[i];
*/
p2 = f;
return retval;
}
如有任何帮助,我们将不胜感激。
I'm creating a managed C++/CLI DLL that wraps and makes available a single function that resides in a c++ static library.
I got most of it working, except one persistent nagging point.
Here's how the function looks like in my unmanaged lib's .h file.
typedef struct
{
float a;
float b;
}MyStruct;
bool GetData(float p1, float* p2, MyStruct buffer[]);
and here's what I have so far on the C++/CLI wrapper:
H file:
using namespace System::Runtime::InteropServices
public ref struct MyManagedStruct
{
float a;
float b;
}
public ref class Wrapper
{
bool static GetDataManaged(
float p1, [Out] float %p2,
array<MyManagedStruct^> ^ managedBuffer);
}
CPP file:
bool Wrapper::GetDataManaged(
float p1, [Out] float %p2,
array<MyManagedStruct^> ^ managedBuffer)
{
float f;
//managed buffer is assumed allocated by the .net caller
MyStruct* unmanagedBuffer = new MyStruct[managedBuffer->Length];
bool retval = GetData(p1, &f, unmanagedBuffer);
/* this doesn't work... any better suggestions?
for (int i=0;i<n;i++)
BallDatabuffer[i] = buffer[i];
*/
p2 = f;
return retval;
}
Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将数据从非托管结构获取到托管结构的一种方法是为托管结构声明一个构造函数,该构造函数接受对非托管结构的引用,如下所示:
请注意构造函数的
internal:
可见性接受非托管结构,因此您不希望它从 C++/CLI DLL 外部可见。声明此构造函数后,您可以编写:
One way you can get the data from your unmanaged struct to the managed struct is to declare a constructor for the managed struct that accepts a reference to the unmanaged struct like so:
Note the
internal:
visibility as the constructor accepts an unmanaged struct, so you don't want it visible from outside the C++/CLI DLL.With this constructor declared you can then write: