C# 将指针从非托管代码传递到托管代码 我有一个简单的C++类,它有两种不同的方法来传递指针到结构:

C# 将指针从非托管代码传递到托管代码 我有一个简单的C++类,它有两种不同的方法来传递指针到结构:,c#,c++,C#,C++,测试h: struct TestStruct { int first; float second; }; class TestWCM { public: TestWCM(); ~TestWCM(); TestStruct* GetTestStruct(); void GetTestStruct(TestStruct* testStructOut); private: TestStruct* testStruct; }; 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;
}

此类正在被VisualC++类库项目使用:

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++类的第二种方法(见注释代码),我会遇到异常。p>


为什么允许使用指针作为返回值,但在作为参数传递时不允许使用它?

为什么将其标记为C#?您应该使用void GetTestStruct(TestStruct*&testStructOut);而不是void GetTestStruct(TestStruct*testStructOut)@Codor我从一个C#应用程序中调用这个包装器,我认为它可能相关。@Amadeusz我尝试过它,它成功了,但我不明白为什么。我更喜欢使用C++代码。不可能使用原来的方法吗?谢谢首先,您必须编写有效的本机C++代码,然后才能考虑包装它。而且它根本无效,唯一的例外是提醒。声明必须是
TestStruct teststruct2
,调用必须是
test->GetTestStruct(&testStructTwo)*testStructOut=*testStruct向更有经验的团队成员寻求帮助,您需要代码审查。