3

I have a dll which contains this function:

int __stdcall PrnText(char *printtext);

In Windows Forms i have this code to invoke the dll:

[DllImport("Printing.dll", EntryPoint = "PrnText", CharSet = CharSet.Ansi)]
public static extern int PrnText(char *printtext);

When i call the function in C# code i get an error like this : " cannot cast string to char*

PrnText("Hello World");

What parameter should i give to PrnText() to make it work?

Later edit:

  Parameter: printtext
  pointer to string containing text to be printed
Emil Dumbazu
  • 662
  • 4
  • 22
  • 37
  • Looks like it is related to an [answered question](http://stackoverflow.com/questions/1658269/char-pointer-from-string-in-c-sharp). – Andrii Kalytiiuk Jan 29 '12 at 12:10

1 Answers1

3

The CLR knows how to convert a string to an unmanaged char* at runtime. You should use a signature which accepts a string, as such:

public static extern int PrnText(string printtext);

Note that this will work only if the parameter is input only.

Rotem
  • 21,452
  • 6
  • 62
  • 109
  • Do you mean input by the user ? Like a textbox or something? – Emil Dumbazu Jan 29 '12 at 12:15
  • It will only work if the code you're calling does not need to edit the string. In that were the case, you'd need to pass a `StringBuilder`, since strings are immutable. – diggingforfire Jan 29 '12 at 12:17
  • @Emil No, I mean input only as in the dll function is not changing the `char*` in any way. – Rotem Jan 29 '12 at 12:17
  • @EmilDumbazu: no, it means you can only pass a string as an input parameter to your native code - it won't be able to modify it. If your native function needs to mutate a string, pass a `StringBuilder` instead. – vgru Jan 29 '12 at 12:20
  • could you give me an example with StringBuilder ? – Emil Dumbazu Jan 29 '12 at 12:56
  • see this question: http://stackoverflow.com/questions/2179270/pass-c-sharp-string-to-c-and-pass-c-result-string-char-whatever-to-c-s – Rotem Jan 29 '12 at 13:48
  • Or in other words, the C declaration is wrong. It should have declared the argument as `const char*`. This is a common oversight. – Hans Passant Jan 29 '12 at 16:57