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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I don’ think OP wants a string. Looking at the example data provided in the question, I think byte[] would be more appropriate.
@KonradRudolph - They can just convert the String into a byte[] in that case. Who knows what the author want their question was vague.
The example in the question clearly puts characters into an array in a method called getSerialNumber, which clearly means to retrieve a text string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.