0

Good day!

I have strange problem. On Delphi side we have:

Function Func(str: String; res: double) : double; export; stdcall;
Begin
    Result := res;
End;

And on C# side:

[DllImport("Project1.dll")]
static extern double Func(string str, double res);

It's OK, if i will write like this:

Console.WriteLine(Func("this is my function", 0.1));

Result will be 0.1.

But if I will replace 0.1 with 0 (zero, and 0d, and 0.0 too), I will get SEHException (0x80004005).

Any ideas?

UPD.

Delphi 2007 (no way to change, too many to rebuild ^_^)

VS 2013 (.NET 4.5.1)

OS: Windows 8.1

Platform target x86 (in x64 it does not work at all).

4

2 Answers 2

0
Function Func(str: String; res: double): double; stdcall;

This function can only be called from Delphi because it uses the native Delphi string type. Indeed you can only call it from a Delphi version that has a binary compatible string type.

If you wish to interop with C# you will need to change your signature to use types that are valid for interop. For instance:

Function Func(str: PAnsiChar; res: double): double; stdcall;

On the C# side this is:

[DllImport(dllname, CharSet = CharSet.Ansi)]
static extern double Func(string str, double res);

As an alternative to using null-terminated character arrays, you could use the COM BSTR type if you preferred. I won't demonstrate that here. There are plenty of examples already available.

4
  • This is becoming a bit of an 'old chestnut'. Has anyone come up with a C# class that CAN be passed as a Delphi string? Would it be useful?
    – Hugh Jones
    Commented Nov 3, 2014 at 14:32
  • @Hugh easier to use either option in the Q in my view. Interop should be language agnostic. Commented Nov 3, 2014 at 15:29
  • Yes, of course - but the OP and others are faced with situations where they cannot change the Delphi .dll
    – Hugh Jones
    Commented Nov 3, 2014 at 17:48
  • @hugh The answer there is to recompile with a corrected interface. If that cannot be done then a delphi wrapper ois needed. Commented Nov 3, 2014 at 17:56
-1

try

Console.WriteLine(Func("this is my function", Convert.ToDouble(0.0)));
5
  • With Convert.ToDouble(0.0) AccessViolationException: Attempted to read or write protected memory. But it's still all right with Convert.ToDouble(0.1)
    – Spawn
    Commented Nov 2, 2014 at 9:05
  • how about double dbl_value = 0; Console.WriteLine(Func("this is my function", dbl_value)); Commented Nov 2, 2014 at 10:22
  • The C# compiler is perfectly capable of passing a double value of 0.0. Commented Nov 2, 2014 at 12:58
  • As I understand, Delphi gets params from stack by reference, and 0 is Zero reference. So IntPtr should help. Commented Nov 3, 2014 at 9:44
  • No. The problem is nothing to do with passing the double. You've presented multiple ways to do exactly what is done in the Q. The problem is the other parameter. Commented Nov 4, 2014 at 17:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.