473,324 Members | 2,356 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

Interoping classes

Udi
Hi,
How do I work with a C++ class that is given through a dll?
can someone please give me a short C# example of how to work with the
following code?
Thanks!
class MyClass
{
private:
char * m_data;
public:
MyClass(){...}
int DoSomthing(char * buf){...}
}

Nov 17 '05 #1
5 1992

"Udi" <Ud**********@gmail.com> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com...
Hi,
How do I work with a C++ class that is given through a dll?
can someone please give me a short C# example of how to work with the
following code?
Thanks!
class MyClass
{
private:
char * m_data;
public:
MyClass(){...}
int DoSomthing(char * buf){...}
}


If you mean to call a method in a C++ DLL:

[DllImport("KERNEL32.DLL", EntryPoint="MoveFileW", SetLastError=true,
CharSet=CharSet.Unicode, ExactSpelling=true,
CallingConvention=CallingConvention.StdCall)]
public static extern bool MoveFile(String src, String dst);

The above is from the VS.NET docs. Look at DLLImportAttribute class for
more information. Make sure you have a reference to the DLL in your project.

Brett
Nov 17 '05 #2

"Udi" <Ud**********@gmail.com> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com...
Hi,
How do I work with a C++ class that is given through a dll?
can someone please give me a short C# example of how to work with the
following code?
Thanks!
class MyClass
{
private:
char * m_data;
public:
MyClass(){...}
int DoSomthing(char * buf){...}
}


You can't directly access unmanaged C++ code from C# and you can't PInvoke
native C++ class member functions.
So what you should do is author a managed wrapper class using VS2003 ME C++
(or the upcoming C++/CLI ) that serves as a thunk.

Here's a sample...

#include "nativeheader.h"
#include <vcclr.h> // needed for PtrToStringChars
// Wrapper class
public __gc class MyClassWrapper
{
private:
MyClass* mc;
public:
MyClassWrapper() : ac( new MyClass()){}
int DoSomthing(System::String buf)
{
// convert String to char*
__const_Char_ptr wch = PtrToStringChars( buf );
return mc->DoSomthing(buf);
}
~MyClassWrapper() {
delete mc;
}
};
in C#, add a reference to the wrapper DLL and use the class like any other
managed class:

...
MyClassWrapper mcw = new MyClassWrapper();
mcw.DoSomthing(...);

You might find much more info on the VC++ MSDN site
http://msdn.microsoft.com/visualc/

Willy.
Nov 17 '05 #3

"Brett Romero" <no@spam.net> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...

"Udi" <Ud**********@gmail.com> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com...
Hi,
How do I work with a C++ class that is given through a dll?
can someone please give me a short C# example of how to work with the
following code?
Thanks!
class MyClass
{
private:
char * m_data;
public:
MyClass(){...}
int DoSomthing(char * buf){...}
}


If you mean to call a method in a C++ DLL:

[DllImport("KERNEL32.DLL", EntryPoint="MoveFileW", SetLastError=true,
CharSet=CharSet.Unicode, ExactSpelling=true,
CallingConvention=CallingConvention.StdCall)]
public static extern bool MoveFile(String src, String dst);

The above is from the VS.NET docs. Look at DLLImportAttribute class for
more information. Make sure you have a reference to the DLL in your
project.

Brett


No, this won't work. The class is a native C++ class, you can't (and you
shouldn't) set references to native code DLL's and you can't call member
functions in native classes fom C#.

Willu.
Nov 17 '05 #4
Udi
Thanks Willy!
I really appreciate it!
What if I need an out string parameter?
I mean PtrToStringChars returns a const char, what is the right way to
initialize it inside
MyClass and return it back from the wrapper?

int DoSomthing(out System::String * buf)
{
// convert String to char*
__const_Char_ptr wch = PtrToStringChars( buf );
return mc->DoSomthing( wch ); --> need it out here!
}

Nov 17 '05 #5

"Udi" <Ud**********@gmail.com> wrote in message
news:11*********************@g47g2000cwa.googlegro ups.com...
Thanks Willy!
I really appreciate it!
What if I need an out string parameter?
I mean PtrToStringChars returns a const char, what is the right way to
initialize it inside
MyClass and return it back from the wrapper?

int DoSomthing(out System::String * buf)
{
// convert String to char*
__const_Char_ptr wch = PtrToStringChars( buf );
return mc->DoSomthing( wch ); --> need it out here!
}


Difficult to answer, it depends who allocated the buffer holding the string,
what allocator has been used and what string type it is (ansi, unicode).
Following sample that assumes the callee (native code) allocates and
returns an ansi string.

// managed wrapper
int SomeWrapper::RetString(System::String** buffer)
{
// allocate native memory to hold the pointer to the char* returned by
callee
System::IntPtr pointerTobufPointer =
Marshal::AllocHGlobal(sizeof(void*));
int ret = ac->RetString(static_cast<char**>(pointerTobufPoint er
..ToPointer()));
if (buf != 0)
{
*buffer =
Marshal::PtrToStringAnsi(Marshal::ReadIntPtr(point erTobufPointer ));
}
return ret;
}

// native C++
int SomeClass::RetString(char** buffer)
{
s = "Hello Ansi world";
*buffer = const_cast<char*>(s.c_str());
return s.length();
}

...
std::string s;

// In C#
SomeWrapper sw = new SomeWrapper();
int ret = sw.RetString(ref s);
...

Note that - I suggets you read all possible documents and white papers found
on http://msdn.microsoft.com/visualc/, and as your questions relate to C++
you might better post to the vc NG microsoft.public.dotnet.languages.vc

Willy.
Nov 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Bob Rock | last post by:
Hello, in the last few days I've made my first few attempts at creating mixed C++ managed-unmanaged assemblies and looking aftwerwards with ILDASM at what is visible in those assemblies from a...
9
by: Jack | last post by:
Hello I have a library of calculationally intensive classes that is used both by a GUI based authoring application and by a simpler non-interactive rendering application. Both of these...
9
by: Aguilar, James | last post by:
I know that one can define an essentially unlimited number of classes in a file. And one can declare just as many in a header file. However, the question I have is, should I? Suppose that, to...
12
by: Langy | last post by:
Hello I'm fairly new to C++ but have programmed several other languages and found most of c++ fairly easy (so far!). I've come to a tutorial on classes, could someone please tell me why you...
4
by: john townsley | last post by:
do people prefer to design classes for the particular job or for a rangle of tasks they might encounter now and in the future. i am doing some simple win32 apps and picking classes is simple, but...
2
by: joye | last post by:
Hello, My question is how to use C# to call the existing libraries containing unmanaged C++ classes directly, but not use C# or managed C++ wrappers unmanaged C++ classes? Does anyone know how...
18
by: Edward Diener | last post by:
Is the packing alignment of __nogc classes stored as part of the assembly ? I think it must as the compiler, when referencing the assembly, could not know how the original data is packed otherwise....
6
by: ivan.leben | last post by:
I want to write a Mesh class using half-edges. This class uses three other classes: Vertex, HalfEdge and Face. These classes should be linked properly in the process of building up the mesh by...
0
by: ivan.leben | last post by:
I am writing this in a new thread to alert that I found a solution to the problem mentioned here: http://groups.google.com/group/comp.lang.c++/browse_thread/thread/7970afaa089fd5b8 and to avoid...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.