简体   繁体   English

通过在C#中导入DLL重新使用C ++函数

[英]Re-using C++ functions by importing DLL in C#

I've general questions while importing a C++ created DLL into C#. 将C ++创建的DLL导入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. 1)我已经编写了利用指针(例如双指针,指针数组等)的C ++函数。例如static int someFunc(char *var[])如何重用它们,因为C#不支持指针。

2) Do I need to expose all the functions through [DllImport()] in C#? 2)我需要通过C#中的[DllImport()]公开所有功能吗? ie I've a function called someFunc which calls other functions internally. 即我有一个名为someFunc的函数,该函数在内部调用其他函数。 Should I expose those functions too under 'DllImport' 我是否也应该在“ DllImport”下公开这些功能

3) Can anyone please explain why I require to handle the unmanaged code in C# especially when I import dlls from C++? 3)谁能解释为什么我需要处理C#中的非托管代码,尤其是当我从C ++导入dll时?

Point 1 Answer: use the unsafe keyword in function declaration in C# 要点1答案:在C#中的函数声明中使用unsafe关键字

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

point 2 Answer: There is no need to import all functions. 要点2答案:无需导入所有功能。 only import someFunc() 只导入someFunc()

point 3 answer: C# uses managed code which is type safe and refers to some valid memory location. 第3点答案:C#使用托管的代码,该代码是安全类型的,并且指向某些有效的内存位置。 However pointers as in C++ may or may not refer to any valid memory location. 但是,C ++中的指针可能会或可能不会指向任何有效的内存位置。 So you need to handle unmanaged code in C#. 因此,您需要使用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. C#确实在不安全区域中支持指针,但是,您也可以使用IntPtr,它类似于C ++的void * DllImport,其中IntPtr作为参数或返回值。

The correct thing to do, however, would be to use marshaling to automatically translate char* to System.String and vise versa. 但是,正确的做法是使用封送处理将char *自动转换为System.String,反之亦然。 (And to translate an array of char* to an array of strings .) (并将char *数组转换为字符串数组 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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