Return value from C++ dll called from C# app

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How would I do, in both ends, to get a return value from a C++ dll called
from C# app?
 
More specifically, I would like the return value to be a HRESULT (as it
already is), but I would like to pass a parameter which I can change in the
DLL so that it also has effect in the C# app.
 
More specifically, I would like the return value to be a HRESULT (as it
already is), but I would like to pass a parameter which I can change in the
DLL so that it also has effect in the C# app.

So something like this?

HRESULT _stdcall MyFunc(int *pi)
{
if (!pi) return E_POINTER;
*pi = 42;
return S_OK;
}

---

[DllImport("your.dll")]
static extern uint MyFunc(ref int pi);

....

int i = 0;
uint hr = MyFunc(ref i);


Mattias
 
Mattias Sjögren said:
So something like this?

HRESULT _stdcall MyFunc(int *pi)
{
if (!pi) return E_POINTER;
*pi = 42;
return S_OK;
}


Works, but bleech, you need untrusted code permission. If you can compile
the C++ code as a managed assembly (C++/CLI), then you would use

public ref class A
{
HRESULT MyFunc(System::Int32% intbyref) { intbyref = 42; return S_OK; }
}

which has almost the identical caller interface, but no need for DllImport
(use a managed reference instead) and needs no special permissions (since
this code will compile with /clr:safe)
 
Ben Voigt said:
Works, but bleech, you need untrusted code permission. If you can compile the C++ code as
a managed assembly (C++/CLI), then you would use

public ref class A
{
HRESULT MyFunc(System::Int32% intbyref) { intbyref = 42; return S_OK; }
}

which has almost the identical caller interface, but no need for DllImport (use a managed
reference instead) and needs no special permissions (since this code will compile with
/clr:safe)

True, but the OP is talking about existing native C++ code I guess, Mattias is only
illustrating, by example, how you can declare a function that returns an HRESULT and passes
a value by reference.
Note that you can apply the "SuppressUnmanagedCodeSecurityAttribute" to suppress the
security walk when using PInvoke, this achieves the same result as C++/CLI's managed/native
code interop.

Wily.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top