Wrapper Component in C++/CLI to use Legacy C++ code/functionality in C#

S

Subodh

Hi,

We have legacy code in C/C++, I am writing a wrapper component in C++/
CLI that will allow using this legacy code functionality in C#, I have
linked all my static libraries to this C++/CLI DLL project
I have created a wrapper public static ref class in C++/CLI project
that will expose functions for the C# client.

Problem:
when I use a function that returns a pointer or that has pointer
arguments, in the C++/CLI project, The C# client where this wrapper
component is referenced, gives a runtime error when i try to access
the wrapper function,
Error:
"The handle is invalid. (Exception from HRESULT: 0x80070006
(E_HANDLE))"

How do I use functions that accept/return pointer arguments in my C++/
CLI component so that I can use the functionality in C#??

C++/CLI code
#pragma managed
public ref class LibFunctions
{
public:
static String^ GetDefaultMgr(void)
{
get_default_manager(); //this is a c function that returns
a TCHAR*
}
};

C# client code:
private void DefMgr_Click(object sender, EventArgs e)
{
try
{
MessageBox.Show(LibFunctions.GetDefaultMgr());
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
 
B

Ben Voigt [C++ MVP]

Subodh said:
Hi,

We have legacy code in C/C++, I am writing a wrapper component in C++/
CLI that will allow using this legacy code functionality in C#, I have
linked all my static libraries to this C++/CLI DLL project
I have created a wrapper public static ref class in C++/CLI project
that will expose functions for the C# client.

Problem:
when I use a function that returns a pointer or that has pointer
arguments, in the C++/CLI project, The C# client where this wrapper
component is referenced, gives a runtime error when i try to access
the wrapper function,
Error:
"The handle is invalid. (Exception from HRESULT: 0x80070006
(E_HANDLE))"

How do I use functions that accept/return pointer arguments in my C++/
CLI component so that I can use the functionality in C#??

C++/CLI code
#pragma managed
public ref class LibFunctions
{
public:
static String^ GetDefaultMgr(void)
{
get_default_manager(); //this is a c function that returns
a TCHAR*

Here you have a non-void function without a return statement. You should
have gotten a compiler warning for that, and naturally the result is no
good.

Make sure you return a valid String^, created using Marshal::ptrToStringAnsi
or Marshal::ptrToStringUni depending on whether UNICODE is defined.
 

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

Top