I want to call a C# function from C++ , via CLI/C++.
C# code
private string _text = " ";
public void setText(string text)
{
// _text = text;
_text = "HI World";
}
Ideally setText shall have the commented line only. The _text = "HI World" is an example.
public string getText()
{
return _text;
}
C++/CLI code
Header :
gcroot<Bridge> _managedObject;
virtual void setText(std::string text);
virtual std::string getText();
CPP file
std::string CStringBridge::getText()
{
// _managedObject = gcnew Bridge(); return (marshal_as(_managedObject->getText())); }
void CStringBridge::setText(std::string text)
{
// _managedObject = gcnew Bridge(); _managedObject->setText(gcnew System::String(text.c_str())); }
IStringBridgeWrapper* IStringBridgeWrapper::CreateInstance(void)
{
return ((IStringBridgeWrapper *)new CStringBridge());
}
Note : When I use the following code
virtual void setText(System::String^ text);
virtual System::String^ getText();
I get the following error 3395
*__declspec(dllexport) cannot be applied to a function with the __clrcall calling convention*
, and so I stuck to std::string
When I use the library from the C++/CLI code, and call from my C++ program, "Hi World" should be printed ; instead nothing gets printed
C++ console application
IStringBridgeWrapper *pBridge = IStringBridgeWrapper::CreateInstance();
pBridge->setText(std::string("I am here"));
pBridge->getText();
I think the string is not being properly passed .
Any ideas to solve it shall be appreciated.
EDIT
I have updated the code after the comments , yet nothing shows up.
gcroot creates a handle, but does not allocate memory for it. But as Bridge has no memory allocated , the application does not work.My code is in the same lines at the article here - http://www.codeproject.com/Articles/10020/Using-managed-code-in-an-unmanaged-application .
Bridge
in the CPP/CLIgetText
function, if I understand correctly, won't that reset the_text
object in your C# class? – Zaid Amir