本文介绍了用CString调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用P/Invoke从C#调用非托管C ++ DLL中的函数. C ++ DLL使用CString作为函数参数并返回,例如

I'm trying to use P/Invoke to call functions in an unmanaged C++ DLL from C#. The C++ DLL uses CString's as function parameters and returns, such as

CString AFX_EXT_API GetUserName(CString& userID)

不幸的是,C ++是旧代码,我无法更改为使用更通用的LPSTR(甚至是char *).

Unfortunately, the C++ is legacy code that I cannot change to use the more universal LPSTR (or even char *).

是否有任何方法可以将CString编组为.NET兼容对象?还是以某种方式装饰.NET char[]以封送至CString?

Is there any way to marshal the CString into a .NET compatible object? Or somehow decorate a .NET char[] to be marshaled to a CString?

推荐答案

您无法在托管代码中创建CString.因此,显然,在托管代码和本机代码之间需要一个额外的层.

You can't create a CString in managed code. So clearly you need an extra layer between the managed code and the native code.

这为您提供了一个制作介于两者之间的C ++/CLI DLL的机会.您可以从托管程序集中调用此代码,而无需P/invoke.从C ++/CLI中间层,您可以创建CString.

This gives you an opportunity to make a C++/CLI DLL which sits between. You can call this code from your managed assembly without needing P/invoke. And from the C++/CLI middle layer you can create a CString.

但是,有一个警告.您必须使用与本地DLL相同的C ++运行时.这可能是可行的,但很有可能会成为绊脚石.例如,如果DLL是用MSVC6编写的,那么您也将需要用MSVC6构建中间层,这将排除C ++/CLI.在这种情况下,请返回P/invoke和char*.

However, there is one caveat. You must be using the same C++ runtime as the native DLL. This may be possible but it is quite likely that it will be a stumbling block. For example if the DLL was written with MSVC6 then you will need to build your intermediate layer with MSVC6 too and that rules out C++/CLI. Back to P/invoke and char* in that case.

我要强调的是,基于CString导出DLL接口是一种糟糕的做法,我会寻找DLL的替代方案.

I would stress that it is terrible practice to export a DLL interface based on CString and I'd be looking for alternatives to the DLL.

这篇关于用CString调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 20:46