开发者

How do I call a function defined in a C++ DLL that has a parameter of type int *, from inside C# code?

I have a native regular C++ Dll which I want to call from C# code, so i created C++/CLI class (as described here and here) which will include managed C++ code and which can be ca开发者_开发百科lled by any C# code directly and which can make calls inturn to native unmanaged C++.

One of function in native C++ dll has parameter of type int *. How do I declare in wrapper function and how can i convert it into int *?


It is the C/C++ way of passing a value by reference. You should use the ref or out keyword:

[DllImport("something.dll")]
private static extern void Foo(ref int arg);

In C++/CLI that would look roughly like this:

public ref class Wrapper {
private:
    Unmanaged* impl;
public:
    void Foo(int% arg) { impl->Foo(&arg); }
    // etc..
};


[DllImport("some.dll")]
static extern void SomeCPlusPlusFunction(IntPtr arg);

IntPtr is a type that is roughly equivalent to void *.

From your comment, you'd be best off doing something like this (C#):

int size = 3;
fixed (int *p = &size) {
    IntPtr data = Marshal.AllocHGlobal(new IntPtr(p));
    // do some work with data
    Marshal.FreeHGlobal(data); // have to free it
}

but since AllocHGlobal can take an int, I don't know why you wouldn't do this:

IntPtr data = Marshal.AllocHGlobal(size);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜