C ++ / CLI双指针类型转换为ref IntPtr的为C#访问 [英] C++/CLI double pointer typecasting to ref IntPtr for C# access
问题描述
我在C ++ / CLI写周围的C DLL的包装,以便它可以在C#中通过托管程序进行访问。使用直接的P / Invoke通过C#来访问C函数,因为C DLL引发的异常不能被正确地使用P / Invoke(异常消息跨C / C#边界移动时丢失)抓是不可能的。这样的想法是创建一个托管CLI DLL在内部调用C DLL并包装异常Exception类的CLI。
所以C DLL函数本声明。
无效在initdb (无效**手柄);
在C#应用程序将需要进行以下声明
无效InitDB_cs(参考IntPtr的手柄);
要做到这一点,我创建C ++ / CLI函数如下声明
无效InitDB_clr(IntPtr的手柄%);
不过,我无法裁判InPtr到类型转换成C函数。我试着用下面的代码,但似乎无法得到正确的类型转换。
无效InitDB_clr(IntPtr的手柄%)
{
pin_ptr< IntPtr的> PTR = handle.ToPointer();
initdb的(安培; PTR);对于上面的代码
}
错误消息
错误C2440:初始化:无法从无效*转换为CLI :: pin_ptr<类型>'
1 GT;与
1 GT; [
1 GT;类型=系统:: IntPtr的
1 GT; ]
1 GT;从无效*为指针,以非'void转换需要有明确的转换
1 GT;错误C2664:'在initdb:;类型> CLI :: pin_ptr<'不能转换参数1'; *'到'无效**'
1 GT;与
1 GT; [
1 GT;类型=系统:: IntPtr的
1 GT; ]
1 GT;指向的类型无关;转换要求reinterpret_cast,C样式转换或函数样式转换
这是一个退出
参数,而不是真的 REF
,是否正确?
尝试
无效InitDB_clr(IntPtr的%手柄)
{
无效* PTR / * = handle.ToPointer()* /;
initdb的(安培; PTR);
手柄= IntPtr的(PTR);
}
取消注释,如果它需要输入/输出。初始化
I am writing a wrapper around C DLL in C++/CLI so that it can be accessed in C# through a managed assembly. Using direct P/Invoke to access C functions via C# is not possible because C DLL raises exceptions which cannot be correctly caught using P/Invoke (exception message is lost when moving across C/C# boundary). So the idea is to create a managed CLI DLL which internally calls C DLL and wraps the exception to Exception class of CLI.
So the C DLL function has this declaration.
void InitDB(void **handle);
The C# app would required following declaration
void InitDB_cs(ref IntPtr handle);
To accomplish this I created C++/CLI function with following declaration
void InitDB_clr(IntPtr %handle);
However, I am unable to typecast ref InPtr into C function. I tried using following code but seems can't get the typecasting right.
void InitDB_clr(IntPtr %handle)
{
pin_ptr<IntPtr> ptr = handle.ToPointer();
InitDB(&ptr);
}
Error message for above code
error C2440: 'initializing' : cannot convert from 'void *' to 'cli::pin_ptr<Type>'
1> with
1> [
1> Type=System::IntPtr
1> ]
1> Conversion from 'void*' to pointer to non-'void' requires an explicit cast
1>error C2664: 'InitDB' : cannot convert parameter 1 from 'cli::pin_ptr<Type> *' to 'void **'
1> with
1> [
1> Type=System::IntPtr
1> ]
1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
That's an out
parameter, not really ref
, correct?
Try
void InitDB_clr(IntPtr% handle)
{
void* ptr /* = handle.ToPointer() */;
InitDB(&ptr);
handle = IntPtr(ptr);
}
Uncomment the initializer if it needs to be in/out.
这篇关于C ++ / CLI双指针类型转换为ref IntPtr的为C#访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!