简体   繁体   中英

Relocate pointer passed as a parameter

I have a method that takes a single unsigned char* as a parameter.

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.

In the body of the method, I call a third party API that returns an array in a similar way.

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#. How do I do that? I tried simple resultArray = result but that only returns an empty array. 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. 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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