简体   繁体   中英

Re-using C++ functions by importing DLL in C#

I've general questions while importing a C++ created DLL into C#.

1) I've written C++ functions making use of pointers such as double pointers, array of pointers etc. eg static int someFunc(char *var[]) How do i re-use them as C# does not support pointers.

2) Do I need to expose all the functions through [DllImport()] in C#? ie I've a function called someFunc which calls other functions internally. Should I expose those functions too under 'DllImport'

3) Can anyone please explain why I require to handle the unmanaged code in C# especially when I import dlls from C++?

Point 1 Answer: use the unsafe keyword in function declaration in C#

static unsafe int someFunc(char* var[]);

point 2 Answer: There is no need to import all functions. only import someFunc()

point 3 answer: C# uses managed code which is type safe and refers to some valid memory location. However pointers as in C++ may or may not refer to any valid memory location. So you need to handle unmanaged code in C#.

C# does support pointers in unsafe regions, however, you can also use IntPtr which is similar to C++'s void* DllImport with IntPtr as parameter or return value.

The correct thing to do, however, would be to use marshaling to automatically translate char* to System.String and vise versa. (And to translate an array of char* to an array of strings .)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM