Hello,
I have a C# managed dll which I want to call from unmanaged C++.
For this I've exposed the functions from the C# code with COM. The code
is printed below.
I have a c# function 'PrintRef' which takes a string as a ref argument
and fills it with an arbitrary value.
However, when C++ calls the 'PrintRef(ref string name)' function, I get
a runtime error.
I don't really understand what is happening here and why it happens.
Can somebody give some insights?
Regards,
Gerben
### C++ code ###
#include "stdafx.h"
#import <mscorlib.tlb> raw_interfaces_only
#import "CSharpServer.tlb" no_namespace named_guids
int main(int argc, char* argv[])
{
CoInitialize(NULL);
IManagedInterface *cp = NULL;
HRESULT hr = CoCreateInstance(CLSID_InterfaceImplementation,
NULL, CLSCTX_INPROC_SERVER,
IID_IManagedInterface, reinterpret_cast<void**>(&cp));
cp->PrintHi("Gerben");
BSTR *bstrname = new BSTR();
cp->PrintRef(bstrname);
// Be a good citizen and clean up COM:
CoUninitialize();
return 0;
}
###
### C# code ###
using System;
using System.Runtime.InteropServices;
namespace CSharpServer
{
// Since the .NET Framework interface and coclass have to behave as
// COM objects, we have to give them guids.
[Guid("DBE0E8C4-1C61-41f3-B6A4-4E2F353D3D05")]
public interface IManagedInterface
{
int PrintHi(string name);
void PrintRef(ref string name);
}
[Guid("C6659361-1625-4746-931C-36014B146679")]
public class InterfaceImplementation : IManagedInterface
{
public int PrintHi(string name)
{
Console.WriteLine("Hello, {0}!", name);
return 33;
}
public void PrintRef(ref string name)
{
name = "123gerben";
}
}
}
###
Richard T. Edwards - 03 Oct 2005 11:51 GMT
What happens when you drop the ref?
> Hello,
>
[quoted text clipped - 71 lines]
> }
> ###
Gerben Heinen - 05 Oct 2005 20:36 GMT
Hi,
It doesn't return with an error. The type it marshals to is then
_bstr_t , but the var isn't filled then. All the parameters are 'not
assigned'.
Do you have more advice?
Kind regards,
Gerben
Richard T. Edwards schreef:
> What happens when you drop the ref?
>
[quoted text clipped - 73 lines]
> > }
> > ###