C# C++/CLI 混合编程类型转化注意事项

微软提供了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 NULL s in your string, the result of marshaling the string is not guaranteed. The embedded NULL s can cause the string to be truncated or they might be preserved.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值