简体   繁体   English

重定位作为参数传递的指针

[英]Relocate pointer passed as a parameter

I have a method that takes a single unsigned char* as a parameter. 我有一个方法,它将一个unsigned char*作为参数。

int MyClass::MyMethod(unsigned char* resultArray)

That parameter is allocated by an external .NET application and passed but the value is expected to change based on the result. 该参数由外部.NET应用程序分配并传递,但预计该值将根据结果更改。

In the body of the method, I call a third party API that returns an array in a similar way. 在方法的主体中,我调用了第三方API,该API以类似的方式返回数组。

ThirdPartyAPI::GetResult(result);
int size = result.GetSize();
unsigned char* temp = new unsigned char[size];
result.GetData(temp);

Now, my temp variable is a filled array with the results I need to return to C#. 现在,我的临时变量是一个填充数组,其中包含我需要返回C#的结果。 How do I do that? 我怎么做? I tried simple resultArray = result but that only returns an empty array. 我尝试了简单的resultArray = result但是只返回一个空数组。 Since there's no way for C# application to know the size prior to calling my method, it must be initialized to a random length or sent in empty and resized in my method. 由于C#应用程序在调用我的方法之前无法知道大小,因此必须将其初始化为随机长度或以空方式发送并在我的方法中调整大小。 So if I could so something like resultArray = new unsigned char[size] to resize it then I could avoid the copy but that throws an exception. 因此,如果我可以像resultArray = new unsigned char[size]来调整其大小,则可以避免该复制,但是会引发异常。

What is the best way to accomplish this? 做到这一点的最佳方法是什么?

If you have a say in the method signature, then change your function to this 如果在方法签名中有发言权,则将功能更改为此

int MyClass::MyMethod(unsigned char** resultArray)

then you can do 那你就可以

*resultArray = result;

To call this method you would now have to pass the address of the pointer rather than just the pointer 要调用此方法,您现在必须传递指针的地址,而不仅仅是指针

MyClass m;
char *str;
m.MyMethod(&str);

Alternative solution 替代解决方案

char* MyClass::MyMethod(int *status);

With this signature, you can just return the string and modify the int parameter to contain the status of the call 使用此签名,您只需返回字符串并修改int参数以包含调用状态

MyClass m;
int status;
char *str = m.MyMethod(&status);
if (status == 0) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM