Your return type is byte[]
in C# but vector<unsigned char>
in C++. These don't match. In your other questions, you were encouraged to fill the array instead of returning it but you still want to return an array, this is how to do it:
Convert the Vector
to array then return it. The C++ return type should be char*
and the C# return type should be IntPtr
. Also, you need a way to tell C# the size of the array. You can do this with an argument. On the C# side, you have to create new array again with the size returned by that argument. After this, use Marshal.Copy
to copy the data from IntPtr
to that new array.
C++:
char* getCPPOutput(int* outValue)
{
//Convert the Vector to array
char* vArrray = &some_vector[0];
*outValue = some_vector.size();
return vArrray;
}
C#:
[DllImport("MySharedObj", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr getCPPOutput(out int outValue);
//Test
void Start()
{
int size = 0;
//Call and return the pointer
IntPtr returnedPtr = getCPPOutput(out size);
//Create new Variable to Store the result
byte[] returnedResult = new byte[size];
//Copy from result pointer to the C# variable
Marshal.Copy(returnedPtr, returnedResult, 0, size);
//The returned value is saved in the returnedResult variable
}
Note about your C++ code:
I did not see your some_vector
variable declaration. If this is declared in that function as a local variable then it's on the stack and you have to allocate new array dynamically with the new
keyword and create a another function to free it with the delete
keyword after receiving it on the C# side. You can't return array on the stack unless it is declared as a static
object or dynamically allocated with the new
keyword.