I have an interface, IProxy, and an implemenation Proxy. The purpose of the proxy is to wrap some extern functions which call into a C library. For the extern declaritions this requires that the structs be passed using the ref keyword. Here's a sample:
namespace CFuncs {
[DllImport("cLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int MyCFunc(ref MyStruct result);
}
public interface IProxy { public int MyFunc(MyStruct result); }
public class Proxy : IProxy {
public int MyFunc(MyStruct result) {
return CFuncs.MyCFunc(ref result);
}
}
The function declartion from the C header file:
int MyCFunc (MY_STRUCT* result);
typedef struct {
// some fields
} MY_STRUCT;
And the calling code:
var proxy = new Proxy();
var result = new MyStruct();
proxy.MyFunc(result);
My question is should I be using ref in the wrapper interface and implemenation as well, or will the struct be properly filled with data by the C function?
EDIT: The code presented as a sample DOES seem to work. Could that be that even though the C library wants a pointer it never actually does change it? Is ref a requirement for interop-ing with functions that take pointers? The sample C code that comes with the library always has the caller allocating memory for the structs it takes, if that means anything.
.NET使用按值调用,而且struct
是一种值类型-因此,如果要由外部函数更改它,则应将其作为ref
参数。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.