Reputation: 1005
I've been trying to create a c# wrapper for a c++ class I have created. I've looked around on how to do this but none of the examples seem to use classes and objects. I have the following code in c++:
#ifndef PORTAUDIOMANAGER_H
#define PORTAUDIOMANAGER_H
#include "portaudio.h"
#include "pa_asio.h"
class PortAudioManager
{
public:
PortAudioManager();
virtual ~PortAudioManager();
static PortAudioManager* createObject();
void openStream();
void dispose(PortAudioManager* obj);
void stopStream();
typedef struct
{
float left_phase;
float right_phase;
}
paTestData;
private:
void* stream;
paTestData data;
static PortAudioManager* audioManager;
};
#endif
The createObject
method creates a new object of PortAudioManager and registers it to the audioManager pointer. The dispose
method acts as the destructor (since I thought you can't use the constructor and destructor in C#).
So how it should be used is simply like this:
PortAudioManager manager = PortAudioManager.createObject();
manager.openStream();
How would I go about creating a system that this can be used in c#? If you need more information, let me know.
Upvotes: 1
Views: 100
Reputation: 699
Create a new class library project and compile with the /clr flag. Given the native C++ class presented above, add the following C++/CLI class to wrap your native class:
public ref class PortAudioManagerManaged
{
private:
PortAudioManagerManaged(PortAudioManager* native)
: m_native(native) { }
public:
PortAudioManagerManaged()
: m_native(new PortAudioManager) { }
// = IDisposable.Dispose
virtual ~PortAudioManagerManaged() {
this->!PortAudioManagerManaged();
}
// = Object.Finalize
!PortAudioManagerManaged() {
delete m_native;
m_native = nullptr;
}
static PortAudioManagerManaged^ CreateObject()
{
return gcnew PortAudioManagerManaged(PortAudioManager::createObject());
}
void OpenStream()
{
if (!m_native)
throw gcnew System::ObjectDisposedException(GetType()->FullName);
m_native->openStream();
}
void StopStream()
{
if (!m_native)
throw gcnew System::ObjectDisposedException(GetType()->FullName);
m_native->stopStream();
}
private:
PortAudioManager* m_native;
};
In your C# project, add a reference to your C++/CLI class library.
using (PortAudioManagerManaged manager = PortAudioManagerManaged.CreateObject())
{
manager.OpenStream();
}
Upvotes: 2