Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

shame , i deleted my mingw-opencv dlls, so i can't test on the real thing, but the general aproach would be like this:

1

say, you got a my.cpp with simple functions, like

const char * myfunc() {
    return "helo world";
}
void otherfunc( double z, int o ) {
}

make a dll from the c++ code:

gcc my.cpp -shared -o my.dll

ofc, link to the opencv libs as well

2

in your c# code you need the interop services, and dllimport any func from the dll you use:

using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        [DllImport("my.dll", CharSet = CharSet.Ansi)]
        private extern static string myfunc();
        [DllImport("my.dll", CharSet = CharSet.Ansi)]
        private extern static void otherfunc(double z,int o);

then you can just call them like any other c# function

MessageBox.Show(myfunc());

3

caveats and downsides ;)

  • stick to simple functions and most 'atomic' types. marshalling classes isn't for the weak of heart (like me)
  • if you actually return pointers ( like, e.g pixels ) make sure, you don't return temporary objects, that get invalidated when leaving the function's scope. that might even require global vars or such.
  • you're dealing with inter-process communication here, you'll probably need CRITICALSECTION in the c++ code, and lock {} on the other side

shame , i deleted my mingw-opencv dlls, so i can't test on the real thing, but the general aproach would be like this:

1

say, you got a my.cpp with simple functions, like

const char * myfunc() {
    return "helo world";
}
void otherfunc( double z, int o ) {
}

make a dll from the c++ code:

gcc my.cpp -shared -o my.dll

ofc, link to the opencv libs as well

2

in your c# code you need the interop services, and dllimport any func from the dll you use:

using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        [DllImport("my.dll", CharSet = CharSet.Ansi)]
        private extern static string myfunc();
        [DllImport("my.dll", CharSet = CharSet.Ansi)]
        private extern static void otherfunc(double z,int o);

it has to find the dll as well, so it must be on the PATH or with your c# app.

then you can just call them like any other c# function

MessageBox.Show(myfunc());

3

caveats and downsides ;)

  • stick to simple functions and most 'atomic' types. marshalling classes isn't for the weak of heart (like me)
  • if you actually return pointers ( like, e.g pixels ) make sure, you don't return temporary objects, that get invalidated when leaving the function's scope. that might even require global vars or such.
  • you're dealing with inter-process communication here, you'll probably need CRITICALSECTION in the c++ code, and lock {} on the other side