Calling async methods in a c# dll from delphi

236 Views Asked by At

I'm writing a DLL in C# which goal is to communicate with a web platform using REST. It's going to be used in a Delphi XE program. The problem is, I don't really know how to go about exposing my DLL methods to be visible in Delphi. Basically all of them look something like:

public async Task<string> foo(string bar)
{
    string result = await client.GetSomethingAndReturnString(bar);

    return result;
}

Is it possible to use those methods from the DLL without registering it? Do I need some sort of a "bridge" in c++ between my library and the target program?

All parameters and return values are strings and I've read about marshalling etc. so I think making the conversion work won't be such a hassle, there are many threads about that.

I won't be writing the Delphi side, however I could have input on how my DLL would be implemented, if that is an important factor.

1

There are 1 best solutions below

3
Petter Hesselberg On BEST ANSWER

A quick fix is to convert the async method to something synchronous:

public string Foo(string bar)
{
    string result = client.GetSomethingAndReturnString(bar).Result;
    return result;
}

Retrieving the Result property will wait until the function is done. Unless the task is cancelled or throws an exception. Slightly improved version:

try
{
    return new Client().GetSomethingAndReturnString(bar).Result;
}
catch (Exception e)
{
    return e.Message;
}

(Though returning the exception message as data is probably not what you want.)

Or you can wait for the task to finish and inspect the result:

Task<string> task = new Client().GetSomethingAndReturnString(bar);
task.Wait();
return task.IsCompleted ? task.Result : "ERROR!";