C# C++/CLI 混合编程类型转化注意事项
来源:互联网 发布:信誉好的单车淘宝店 编辑:程序博客网 时间:2024/04/30 05:45
微软提供了msclr::interop用来实现托管类型和本地类型的转化。
示例代码如下:
#include <stdlib.h>
#include <string.h>
#include <msclr/marshal.h>
using namespace System;
using namespace msclr::interop;
int main() {
const char* message = "Test String to Marshal";
wchar_t *wstr = L"Hello";
String^ result;
result = marshal_as<String^>( wstr );
return 0;
}
但是在转换过程中有的需要context,有的不需要context。
依据如下:(摘自msdn)
Marshaling requires a context only when you marshal from managed to native data types and the native type you are converting to does not have a destructor for automatic clean up. The marshaling context destroys the allocated native data type in its destructor. Therefore, conversions that require a context will be valid only until the context is deleted. To save any marshaled values, you must copy the values to your own variables.
只有在从托管到本地类型转换并且你所转换的本地类型没有自动删除的析构函数时需要context,marshaling context在它的析构函数中释放掉申请的本地类型。因此,需要context的转换仅仅在context删除之前有效,如果想保存marshled的值,必须把他存在自己重新声明的变量中。
由上可知:
1、托管到本地类型转换需要context,本地类型没有析构函数,因为要负责回收空间
2、对于原生类型转托管类型不需要context
3、在需要context的转换中,转换后的变量要保存到自己重新开辟的空间,否则在context析构时会回收内存
还需要注意一点(摘自MSDN)
If you have embedded NULLs in your string, the result of marshaling the string is not guaranteed. The embedded NULLs can cause the string to be truncated or they might be preserved.
- [C++/CLI] C# C++/CLI 混合编程类型转化注意事项
- C# C++/CLI 混合编程类型转化注意事项
- C#与C++/CLI混合编程
- C#与C++/CLI混合编程
- C++/CLI混合编程不可错过
- C/C++混合编程注意事项
- C和C++混合编程注意事项
- FORTRAN/C/C++混合编程注意事项
- c&c++混合编程的注意事项
- C与C#混合编程
- C++/CLI 中字符串类型的转化: 把System::String转化为std::string
- C++/CLI 中字符串类型的转化: 把std::string转化为System::String
- C/C++ 与 C#混合编程
- C++/CLI C#
- c++/cli调用c#
- C++/CLI 调用 C#
- c++/cli调用c#类库,混合编译时出现 warning C4945 解决方法
- OGRE 本地渲染引擎 与 C++/CLI 托管代码的混合编程(一)
- 变量的内存分配和释放
- test
- base64 编码简单介绍
- oracle lead lag 使用实践
- 系出名门Android(7) - 控件(View)之ZoomControls, Include, VideoView, WebView, RatingBar, Tab, Spinner, Chronometer, ScrollView
- C# C++/CLI 混合编程类型转化注意事项
- 使用truss、strace或ltrace诊断软件的"疑难杂症"
- 开启子线程设置GridVIew数据源
- ASP中Property Let、Property Set、Property Get语句的用法和区别
- public Property let,get和直接用public什么区别?
- Javascript中的Var浅谈
- oracle package
- 系出名门Android(8) - 控件(View)之TextSwitcher, Gallery, ImageSwitcher, GridView, ListView, ExpandableList
- 关于声明()和定义的认识