假设我们有一个纯虚拟C ++类:
class INativeInterface {
public:
virtual ~INativeInterface () {};
virtual LPCWSTR GetString () = 0;
};
然后我们需要在C ++ / CLI中提供此接口的实现:
class HalfManagedImplementation : public INativeInterface {
public:
virtual LPCWSTR GetString () override {
// need to return wchar_t const * pointer which points to the
// data of our managedData string
// pin_ptr is not suitable as it will go out of scope
// what other options do we have here?
// perhaps copying managed string contents to unmanaged heap?
wchar_t * unmanagedString = new wchar_t [managedData->Length + 1];
pin_ptr<const wchar_t> pinnedString = PtrToStringChars (managedData);
wcscpy_s (unmanagedString, managedData->Length + 1, pinnedString);
return unmanagedString;
}
private:
String^ managedData;
void SetString (String^ param){
// do something in .net
managedData = param;
}
};
我的主要问题是:
我是否可以在CRT堆上分配一个本机字符串,并将指针返回给本机C ++代码,就像我上面所做的那样,托管代码分配的内存将由本机代码取消分配? 用法示例:
LPCWSTR data = cppCliObject->GetString ();
// do stuff with returned data or persist it by copying it somewhere else
delete[] data;
当本机C ++代码与C ++ / CLI代码不同时,第一个点是否有效?