I have a little piece of a library that I would like to write a .NET wrapper for. At the moment, I'm using P/Invoke, but since I don't have the library's source code or a whole lot of C knowledge, I'm having a difficult time with marshaling. It works so far (sort of), but it feels like a hack.

Essentially, what this does is takes the SMS_MSG_DATA struct and outputs it to a binary format in the msg_buf byte array. The initial value of msg_buf_len is the size of the byte array, but when the encoding completes, it is set to the number of bytes actually filled.

2 Answers
2

C++/CLI can make this easier because you don't have to write a PInvoke definition. Instead you can just use the original native SMS_MSG_DATA structure directly. You are free to write a better looking wrapper structure which is internally converted to SMS_MSG_DATA. This wrapper structure need not have any ugly PInvoke declaration and can be much more in lines with managed guidelines.

In that case, I still have to know exactly which managed types can be converted to the unmanaged types in the SMS_MSG_DATA struct, right? The issue I'm running into now is that the struct declaration isn't entirely correct, so the data isn't marshaled correctly, causing the Encode method to choke on some of the fields.
–
David BrownDec 9 '09 at 16:44

@David: the difference is that in C++/CLI you would do the conversion yourself (via casts and/or Encoder etc).
–
Pavel MinaevDec 9 '09 at 17:00

This is perfectly reasonable P/Invoke code, though you should make sure that you are not passing Unicode around (check your struct defn.), because all your native declarations seem to take ANSI strings.

C++/CLI doesn't really help you too much here - the place where it makes your life easier is when you want to write some blocks of native code, and make the interface to the C# part simpler. The only thing you could do here, is if on the C# side you really only cared about 1-2 params, you could have the C++/CLI DLL fill out the rest for you and not worry about as much ugly code on the C# side

I don't see how his native declarations take ANSI strings. E.g. unsigned short sAddress[...] - note the short here - seems very much like an UTF-16 string to me!
–
Pavel MinaevDec 9 '09 at 16:58

(Can't edit this, so adding a new one) - Yeah, your problem is Definitely the marshalling of those strings. You're declaring them as Unicode, so it's 2x the space, so you're overwriting the rest of the structure. 1 Char Unicode = 2 Chars ANSI.
–
Paul BettsDec 9 '09 at 16:59

The only options are Ansi, Auto, None, and Unicode. ANSI works fine when encoding, but when I decode it later with another method, the strings come up empty. Unicode is decoded correctly into the original strings.
–
David BrownDec 9 '09 at 17:00