2

C++ win32dll1.dll:

extern "C" __declspec(dllexport) int getSerialNumber(char* outs)
{
    char s[2];
    s[0]='0';
    s[1]='1';

    for(int i=0; i < 2; ++i){
        outs[i] = s[i];
    }
    return 1;
}

C#:

[DllImport("win32dll1.dll")]
public unsafe static extern int getSerialNumber(char* ss);

Not able to pass s in the function

char[] s = new char[2];
getSerialNumber(s);

Shouldn't this work? Why or why not?

Daniel Miladinov
  • 1,582
  • 9
  • 20
Vikas Kumar
  • 519
  • 5
  • 16
  • possible duplicates http://stackoverflow.com/questions/683013/interop-sending-string-from-c-sharp-to-c http://stackoverflow.com/questions/2179270/pass-c-sharp-string-to-c-and-pass-c-result-string-char-whatever-to-c-s http://stackoverflow.com/questions/4455234/passing-string-from-c-to-c-sharp – Rotem Dec 02 '12 at 10:09

1 Answers1

3

You should probably use StringBuilder in the declaration:

[DllImport("win32dll1.dll")]
public unsafe static extern int getSerialNumber(StringBuilder s);

The CLR will automatically translate that to C++ char*, call the function, and then convert the result back and store it in the StringBuider.

Call it with something like this:

var sb = new StringBuilder(2);
getSerialNumber(sb);

The number specifies the initial capacity in characters. In this example, it’s only 2 characters; if the C++ code writes more than that, your app will crash.

Timwi
  • 65,159
  • 33
  • 165
  • 230
  • I don’ think OP *wants* a string. Looking at the example data provided in the question, I think `byte[]` would be more appropriate. – Konrad Rudolph Dec 02 '12 at 10:56
  • @KonradRudolph - They can just convert the `String` into a `byte[]` in that case. Who knows what the author want their question was vague. – Security Hound Dec 02 '12 at 11:15
  • The example in the question clearly puts *characters* into an array in a method called *getSerialNumber*, which clearly means to retrieve a text string. – Timwi Dec 03 '12 at 06:41