[英]Relocate pointer passed as a parameter
我有一個方法,它將一個unsigned char*
作為參數。
int MyClass::MyMethod(unsigned char* resultArray)
該參數由外部.NET應用程序分配並傳遞,但預計該值將根據結果更改。
在方法的主體中,我調用了第三方API,該API以類似的方式返回數組。
ThirdPartyAPI::GetResult(result);
int size = result.GetSize();
unsigned char* temp = new unsigned char[size];
result.GetData(temp);
現在,我的臨時變量是一個填充數組,其中包含我需要返回C#的結果。 我怎么做? 我嘗試了簡單的resultArray = result
但是只返回一個空數組。 由於C#應用程序在調用我的方法之前無法知道大小,因此必須將其初始化為隨機長度或以空方式發送並在我的方法中調整大小。 因此,如果我可以像resultArray = new unsigned char[size]
來調整其大小,則可以避免該復制,但是會引發異常。
做到這一點的最佳方法是什么?
如果在方法簽名中有發言權,則將功能更改為此
int MyClass::MyMethod(unsigned char** resultArray)
那你就可以
*resultArray = result;
要調用此方法,您現在必須傳遞指針的地址,而不僅僅是指針
MyClass m;
char *str;
m.MyMethod(&str);
char* MyClass::MyMethod(int *status);
使用此簽名,您只需返回字符串並修改int參數以包含調用狀態
MyClass m;
int status;
char *str = m.MyMethod(&status);
if (status == 0) {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.