用于C ++ / CLI的对象封送管理到非托管呼叫

时间:2014-08-18 17:04:53

标签: c++-cli

我正在编写C ++ / CLI扩展程序,并且遇到了解决问题的问题。我很感激你的帮助,并希望我通过投射或传递参数犯下一个简单的错误。

首先,这里是我试图打电话的非管理功能的定义(我无法改变):

int getResponse(const RequestObject& requestObj, ResponseObject& responseObj);

其次,我的非托管C ++ RequestObject有一个像这样的定义(我也无法改变):

class RequestObject
{
public:
   RequestObject();
   void addElement(int value, int age);
}

现在,在我的托管C ++ / CLI代码中(使用' IJW'互操作能力),我想调用此函数。您将注意到我有unmanagedClassInstance(它包含上面的getResponse函数定义给出的方法)和ManagedRequestObject reqs(它只是我想要放入RequestObject的托管版本)。

RequestObject* unRequest = new RequestObject();
// Here I'm taking things from a managed version of RequestObject and making
// the unmanaged instances:
for each (ManagedRequestObject^ req in reqs) {
    unRequest->addElement(marshal_as<int>(req->getValue()), 
                          marshal_as<int>(req->getAge()));
}
// Call into the unmanaged object to get the request processed:
ResponseObject* unResponse = new ResponseObject();
int result = unmanagedClassInstance->getResponse(unRequest, unResponse);

你能帮我理解如何正确地将unRequest和unResponse传递给getResponse()函数吗?

1 个答案:

答案 0 :(得分:0)

如果你继续使用非托管对象的指针(你可能想要重新考虑),你应该能够像这样调用非托管函数:

int result = unmanagedClassInstance->getResponse(*unRequest, *unResponse);

但除非绝对必要,否则我建议你这样做:

RequestObject unRequest;
// Here I'm taking things from a managed version of RequestObject and making
// the unmanaged instances:
for each (ManagedRequestObject^ req in reqs) {
    unRequest.addElement(marshal_as<int>(req->getValue()), 
                         marshal_as<int>(req->getAge()));
}
// Call into the unmanaged object to get the request processed:
ResponseObject unResponse;
int result = unmanagedClassInstance->getResponse(unRequest, unResponse);