labstreaminglayer / liblsl-Csharp

C# bindings for liblsl

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

char in C# is not the same thing as char in C++

dmedine opened this issue · comments

This is just a heads up as I ran into this problem in a different project.

Without testing it, I can say for sure that this:

public double pull_sample(char[] sample, double timeout = FOREVER) { int ec = 0; double res = dll.lsl_pull_sample_c(obj, sample, sample.Length, timeout, ref ec); check_error(ec); return res; }
is not going to work. I don't think anyone is using this overload much, which is why it hasn't come up, but the code as is will definitely not populate the C# array with the contents of the C++ array representing the sample. No exception or compiler warning will be issued, but the char[] sample variable on the C# side will always contain 0s. The reason is that in C# a char is not a primitive type, but rather an object that can be either 1 or 2 bytes depending on how it is encoded. Thus, this pointer won't marshal properly from managed to unmanaged code and the contents will simply retain their default initialization values.

The correct way to do this is to use byte[] on the C# side and then convert it to a char array like so:
char[] sample = System.Text.Encoding.ASCII.GetString(byte_sample).ToCharrArray()'

The same issue will occur with pull_chunk(char[,]...)

I don't know if this really matters. I can't see why anyone would need this overload in the C# wrapper. The overload with string works just fine.