不支持混合类型

时间:2013-05-10 20:10:12

标签: visual-studio-2010 dll usb c++-cli

请查看以下标题文件

#pragma once
using namespace UsbLibrary;

ref class MissileLauncher
{
public:
    MissileLauncher(void);

private:
    //Bytes used in command
    unsigned char UP[10];
    unsigned char RIGHT[10];
    unsigned char LEFT[10];
    unsigned char DOWN[10];

    unsigned char FIRE[10];
    unsigned char STOP[10];
    unsigned char LED_OFF[9];
    unsigned char LED_ON[9];

    UsbHidPort USB;
};

我在visual studio professional 2010中使用Visual C ++项目(C ++ / CLI?)。当我运行此代码时,我遇到了很多错误

Error   1   error C4368: cannot define 'UP' as a member of managed 'MissileLauncher': mixed types are not supported 
Error   2   error C4368: cannot define 'RIGHT' as a member of managed 'MissileLauncher': mixed types are not supported  
Error   3   error C4368: cannot define 'LEFT' as a member of managed 'MissileLauncher': mixed types are not supported   
Error   4   error C4368: cannot define 'DOWN' as a member of managed 'MissileLauncher': mixed types are not supported   
Error   5   error C4368: cannot define 'FIRE' as a member of managed 'MissileLauncher': mixed types are not supported   
Error   6   error C4368: cannot define 'STOP' as a member of managed 'MissileLauncher': mixed types are not supported   
Error   7   error C4368: cannot define 'LED_OFF' as a member of managed 'MissileLauncher': mixed types are not supported    
Error   8   error C4368: cannot define 'LED_ON' as a member of managed 'MissileLauncher': mixed types are not supported 

这里,名称空间USBLibrary来自C#dll文件。 UsbHidPort;是来自C#dll

的对象

那么,为什么我会收到此错误?有什么想法吗?

2 个答案:

答案 0 :(得分:7)

在这种特定情况下,这实际上并不是一个问题,至少从可见的情况来看,但是C ++ / CLI编译器试图阻止你射击你的腿,导弹风格。垃圾收集器在压缩堆时移动对象。这使得本机对象非常危险,任何指向它们的指针都将变为无效,并且在您通过它们时会破坏GC堆。收集器无法更新这些指针,它无法找到它们。风险太高,所以编译器只是禁止它。

另一种方法是将这些成员声明为指针,并在类构造函数中使用operator new分配数组。

private:
    unsigned char* UP;
    // etc..
public:
    MissileLauncher() {
        UP = new unsigned char[10];
        // etc..
    }
    ~MissileLauncher() {
        this->!MissileLauncher();
        UP = nullptr;   // Destructor may be called more than once 
    }
    !MissileLauncher() {
        delete[] UP;
        // etc...
    }

请注意析构函数和终结器需要释放这些数组的内存。定义析构函数也会带来客户端程序员必须调用它的负担(Dispose()或在C#客户端程序中使用,在C ++ / CLI程序中删除或堆栈语义),跳过这么小的分配并不是不合理的。最后但并非最不重要的是,考虑理智的解决方案并使用托管数组:

private:
    array<Byte>^ UP;
    // etc..
public:
    MissileLauncher() {
        UP = gcnew array<Byte>(10);
        // etc..
    }

答案 1 :(得分:1)

问题是您正在混合托管和非托管类型,这是编译器警告的含义。该类是托管类,但整数数组计为非托管对象。这会导致垃圾回收问题。在这里阅读所有相关内容:

http://blogs.msdn.com/b/branbray/archive/2005/07/20/441099.aspx

为什么不使用托管数组?

相关问题