在C++/CLI中将System :: IntPtr转换为int*

5 c# c++ interop c++-cli

我试图使用C++/CLI互操作层从C#应用程序调用现有的C++库.我有一个看起来像这样的C++函数:

void doSomething(int* foo, int size);
Run Code Online (Sandbox Code Playgroud)

还有一个C#对象,它包含两个字段,一个IntPtr start和一个int size.我写了一个托管的C++类,看起来像这样:

public ref class Wrapper {
public:
    void run(System::IntPtr itn, int size);
};
Run Code Online (Sandbox Code Playgroud)

现在我想在Wrapper :: run中调用doSomething,并且doSomething可以访问C#对象指向的同一数据块.如果没有副本,我正在尝试做什么,如果是这样,怎么样?

Pet*_*ene 3

要从Wrapper::run调用doSomething ,请尝试强制转换System::IntPtr::ToPointer的返回值,如下所示:

doSomething(reinterpret_cast<int*>(itn.ToPointer()), size);
Run Code Online (Sandbox Code Playgroud)