0

I'm working on NFC-4311E RFID tag reader. I need help marshaling this C++ call:

short OpenReader(HANDLE * hCom, unsigned char LinkType, char *com_port)

To C# code. I used this code:

[DllImport("Reader.dll", CharSet = CharSet.Unicode)]
private unsafe static extern short OpenReader(ref IntPtr hWnd, byte linkType, StringBuilder ip)

I'm new in marshaling.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • from what little I know, you can either use `char[]` or `String` to represent the `char *`. I dont know if `StringBuilder` will work or not, and as such cannot comment conclusively on it. As for the `unsigned char`...if I were writing the call i would probably just use `char` – Nevyn May 16 '13 at 14:47
  • You shouldn't need `unsafe`. Is that definitely the correct character encoding (Unicode)? Note that your C++ function must be declared as "C". Other than that, it looks like it could be ok - but what is your actual problem? `StringBuilder` is only needed if the string is being created by the C++; if you're passing it in, you can just use `string`. – Matthew Watson May 16 '13 at 14:48
  • 1
    CharSet.Unicode is not correct, just omit it or use Ansi. StringBuilder is very likely to be not correct, surely you must specify the COM port name yourself. So just use plain "string". Contact the vendor for any additional help, surely they have a lot of customers that use .NET with their product. – Hans Passant May 16 '13 at 15:12

1 Answers1

0

Firstly, welcome to stack overflow.

Although asking questions is encouraged, you should be aware that your question should contain an actual question. This is not a question, you haven't even stated what the problem you're dealing with is. So make sure you ask questions in the future.

But the way I generally marshal a string is like this:

[DllImport("Reader.dll", CharSet = CharSet.Unicode)]
private static extern short OpenReader(ref IntPtr hWnd, byte linkType, [MarshalAs(UnmanagedType.LPString)] string ip)
antonijn
  • 5,702
  • 2
  • 26
  • 33
  • Thanks all. My code works by removing **unsafe** and using **Ansi** –  May 16 '13 at 17:37