C++/CLI: Public ref struct generates C2011: 'class' type redefinition

落爺英雄遲暮 提交于 2019-11-26 23:26:59

问题


I have a header file in a managed DLL project like so:

Enums.h:

#pragma once
...
public ref struct ManagedStruct {
    Bitmap^ image;
}
...

This header is referenced both from another class in the DLL and from a separate executable. The managed struct alone is generating:

error C2011: 'ManagedStruct' : 'class' type redefinition.

If I move the struct to the main header file in the DLL it works fine, and is publicly accessible, so that's what I'm doing, but I would very much like to learn why this is happening when I just move it to another file.

I have checked all necessary includes and namespaces AND tried the obvious header guards, to no avail; I still get the error.

Thanks very much for any insight!


回答1:


You have to de-tune the traditional C/C++ header file think a bit when you work with managed code. The principal source of type declarations is the assembly metadata. This is very different from the native C/C++ compilation model where you have to have a header file for types that you make visible to other modules.

I'm going to guess that you get this C2011 error in the EXE project. Where you both added a reference to the DLL project assembly (like you should) and used #include on the header file. Like you should not. That's a guaranteed duplicate definition, #pragma once doesn't fix that.

Don't use header files for exported type definitions. Always use assembly references.




回答2:


I Know this question is a bit old, but I'm writing this for future usage: I had the following problem, which was similar: managed DLL had a managed class. managed.h:

 namespace Managed {    
        ref class CManagedClass {...}
    }

in an unamanged class I wanted to use this above class and so in unmanaged.h

#include "managed.h"

in another DLL I also did:

#include "unmanged.h"

which resolved in the type redefinition error. I have found a solution to this issue using the following method: forward declaration in the unmanaged.h

namespace Managed {
    ref class CManagedClass;
}

and include the managed.h in the unmanaged.cpp file as usual.



来源:https://stackoverflow.com/questions/2977534/c-cli-public-ref-struct-generates-c2011-class-type-redefinition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!