C++/CLI - Access native types

  • 首先定义一个本地的类型结构
#pragma once
 
struct NativeStruct
{
};
  • 再定义托管类,在接口中使用本地结构:
#pragma once
 
#include "NativeStruct.h"
 
namespace TestAccessNativePointer {
    public ref class RefClass
    {
    public:
        RefClass(NativeStruct *pData) {}
    };
}
  • 在测试程序中尝试调用该接口
#include "stdafx.h"
#include "../TestAccessNativePointer/NativeStruct.h"
 
using namespace System;
 
int main(array<System::String ^> ^args)
{
    NativeStruct data;
    TestAccessNativePointer::RefClass ^ c = gcnew TestAccessNativePointer::RefClass(&data);
    return 0;
}
  • 提示错误:
testapp.cpp(9): error C3767: 'TestAccessNativePointer::RefClass::RefClass': candidate function(s) not accessible
  • 解决方法:使用 make_public 将本地接口公开
#pragma once

#include "NativeStruct.h"
#pragma make_public(NativeStruct)
 
namespace TestAccessNativePointer {
    public ref class RefClass
    {
    public:
        RefClass(NativeStruct *pData) {}
    };
}
  • 提示
1. make_public指令必须放在全局名字空间下,否则会无效并提示C4384警告: #pragma 'make_public' should only be used at global scope

2. 要保持本地类的可见性的一致性,也就是说要保证当前C++/CLI Library或者App对NativeStruct使用都应用了make_public指令,最简单的方式是在 stdafx.h 中申明该指令,保证所有的cpp都应用了。对于不一致的情况,链接时会报错: error LNK2022: metadata operation failed (80131195) : Custom attributes are not consistent: (0x????)