.net 转换托管C++/跨程序集边界将CLI类型转换为非托管类型 P>已经编写了一些C++/CLI来包装现有的非托管C++库,出现了从托管类型转换为非托管类型的问题。一个简单的例子是将std::string转换为System::string,但该原则适用于许多类型,即array->vector。在编写了一些转换函数之后,我决定将它们打包到一个程序集中,以便可以重用它们。考虑到全局C++/CLI函数在当前程序集之外不可见,我最终得到了这样的结果 public ref class ClassJustToContainStaticFunctions { public: static std::string convert( System::String^ s ) { msclr::interop::marshal_context context; return( context.marshal_as<std::string>( s ) ); } };
我在其他情况下也没有遇到任何问题。但是,make_public不适用于像std::string这样的模板类。请参阅此处了解一些信息 例如,我发现有一些尝试,但它们看起来都很丑陋.net 转换托管C++/跨程序集边界将CLI类型转换为非托管类型 P>已经编写了一些C++/CLI来包装现有的非托管C++库,出现了从托管类型转换为非托管类型的问题。一个简单的例子是将std::string转换为System::string,但该原则适用于许多类型,即array->vector。在编写了一些转换函数之后,我决定将它们打包到一个程序集中,以便可以重用它们。考虑到全局C++/CLI函数在当前程序集之外不可见,我最终得到了这样的结果 public ref class ClassJustToContainStaticFunctions { public: static std::string convert( System::String^ s ) { msclr::interop::marshal_context context; return( context.marshal_as<std::string>( s ) ); } };,.net,stl,c++-cli,interop,mixed-mode,.net,Stl,C++ Cli,Interop,Mixed Mode,我在其他情况下也没有遇到任何问题。但是,make_public不适用于像std::string这样的模板类。请参阅此处了解一些信息 例如,我发现有一些尝试,但它们看起来都很丑陋 所以,在所有这些之后,我的问题是我是否遗漏了一些明显的东西?在我看来,从托管类型转换为非托管类型,特别是对于容器类(如STL.NET Unmanged STL)将是一个常见问题,但经过多次搜索,我在该主题上没有找到太多内容。因为这些函数仅在混合模式编程中需要,将它们包装到一些头文件/静态库中,而不是程序集中。通过这种方式
所以,在所有这些之后,我的问题是我是否遗漏了一些明显的东西?在我看来,从托管类型转换为非托管类型,特别是对于容器类(如STL.NET Unmanged STL)将是一个常见问题,但经过多次搜索,我在该主题上没有找到太多内容。因为这些函数仅在混合模式编程中需要,将它们包装到一些头文件/静态库中,而不是程序集中。通过这种方式,您可以在每个程序中重复使用它们,但您并不依赖于它们的导出。对于您的问题,这不是一个特定的答案,但是,对于这些转换函数,我没有任何像您这样的问题:
static void StringToStdString ( String ^ s, std::string& os )
{
using namespace Runtime::InteropServices;
const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}
static const char * StringToCharPtr ( String ^ s)
{
using namespace Runtime::InteropServices;
const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
return chars;
}
static String^ StdStringToString(const std::string& _is)
{
return gcnew String(_is.c_str());
}
static void StringToStdString ( String ^ s, std::string& os )
{
using namespace Runtime::InteropServices;
const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}
static const char * StringToCharPtr ( String ^ s)
{
using namespace Runtime::InteropServices;
const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
return chars;
}
static String^ StdStringToString(const std::string& _is)
{
return gcnew String(_is.c_str());
}