I am developing a Unity project where I've created a DLL in C++ to integrate with my C# scripts. The C++ function I've written is meant to receive a byte array and its size as input parameters. However, I'm encountering an issue where the byte array and byte array length in C# is different from the data received in C++, leading to unexpected behavior.
Here's a simplified version of my C# and C++ code:
C# code
void OnMessageReceived(CommsMessage message) {
byte[] frameDataByteArray = message.payload.ToByteArray();
int frameDataLength = frameDataByteArray.Length;
Debug.Log("Frame length in C# is: " + frameDataLength);
byte[] output = MyCppFunction(messagePtr, frameDataLength);
}
[DllImport("utility", CallingConvention = CallingConvention.Cdecl)]
public static extern byte[] MyCppFunction(byte[] messagePtr, int messageSize);
C++ code
cv::Mat MyCppFunction(const unsigned char* messagePtr, int messageSize) {
std::cerr << "Received message size in C++: " << messageSize << std::endl;
// Additional processing...
}
The issue arises when I print out the lengths in both C# and C++. The length in C# is correct, but the messageSize variable in C++ seems to be incorrect, showing a significantly larger value.
I'm also assuming that the byte[] I'm passing in is affected by this issue but I haven't been able to properly test it. I'm not very proficient in C++ so I'm assuming there's some obvious explanation for why the memory is getting corrupted. Also I'm going to need to receive a byte[] back from C++ to utilize in my C# script. I'm hoping the answer to the first issue will lead me to the answer for this next issue. But if you're able to help on that front too I'd be appreciative.
I suspect this could be caused by one of the following:
Data Type Mismatch: There might be a mismatch in data types between C# and C++, leading to incorrect interpretation of the byte array size.
Memory Management Issue: There could be a memory management issue, such as memory corruption or incorrect pointer usage, causing the size to be distorted in the C++ function.
Endianness Problem: The discrepancy in values might be due to
endianness differences between C# and C++ platforms.
You need to declare the calling convention as CDecl, and the return value should be
IntPtr, as you need it to dispose theCv:Matvalue you are receivingThe array does not need to be pinned, unless it is expected that the function will use beyond the lifetime of the call. The marshaller will automatically pin it for the call itself.
Consider using a proper OpenCV managed library, if that's what you are doing.