将指针从非托管代码传递到托管代码

时间:2017-01-27 12:13:41

标签: c# c++

我有一个简单的C ++类,它有两种不同的方法来传递指向结构的指针:

Test.h:

struct TestStruct
{   
    int first;
    float second;
};

class TestWCM
{
public:
    TestWCM();
    ~TestWCM();

    TestStruct* GetTestStruct();
    void GetTestStruct(TestStruct* testStructOut);
private:
    TestStruct* testStruct;
};

Test.cpp的:

#include "Test.h"

TestWCM::TestWCM()
{
    testStruct = new TestStruct();

    testStruct->first = 42;
    testStruct->second = 24.4;
}

TestWCM::~TestWCM()
{
    delete testStruct;
}

TestStruct* TestWCM::GetTestStruct()
{

    return testStruct;
}

void TestWCM::GetTestStruct(TestStruct* testStructOut)
{
    testStructOut = testStruct;
}

Visual C ++类库项目正在使用此类:

WCM_Wrapper.h:

#include "C:\Test.h"
#include "C:\Test.cpp"

using namespace System;

namespace WCM_Wrapper_Lib {

    public value struct TestThis
    {
        int first;
        float second;
    };

    public ref class TestWrapper
    {
    public:
        TestWrapper();
        ~TestWrapper();

        TestThis GetTestStruct();
    private:
        TestWCM* test;
    };
}

WCM_Wrapper.cpp:

#include "stdafx.h"

#include "WCM_Wrapper_Lib.h"

WCM_Wrapper_Lib::TestWrapper::TestWrapper()
{
    test = new TestWCM();
}

WCM_Wrapper_Lib::TestWrapper::~TestWrapper()
{
    delete test;
}

WCM_Wrapper_Lib::TestThis
WCM_Wrapper_Lib::TestWrapper::GetTestStruct()
{
    TestStruct* testStruct = test->GetTestStruct();

    TestThis testThis;

    testThis.first = testStruct->first;
    testThis.second = testStruct->second;


    // This causes a null-pointer exception:
    // TestStruct* testStructTwo;
    // test->GetTestStruct(testStructTwo);
    // int first = testStructTwo->first;

    return testThis;
}

我可以从C#Windows窗体项目调用非托管C ++代码并且它工作正常,但如果我使用C ++类的第二种方法(请参阅注释代码),我会得到一个异常。

为什么允许将指针用作返回值,但是当它作为参数传递时却不允许?

0 个答案:

没有答案