Pergunta

I'm writing a C# application that must read the video properties of video files. The only way I've found to do this is with the Microsoft Media Foundation which requires C++.

So far, I've made some progress:

  • I've created a managed C++ assembly which compiles to a DLL.
  • I can call it, with a parameter, from the C# code.
  • It executes and prints the video file properties.

What I would like to do next is have the DLL return an object of video properties (width, height, duration, etc.). Given I'm using C++ managed code, is there a simple way to define an object type and use it to pass data between C# and C++ or do I have to use the Marshal class?

Foi útil?

Solução

Certainly! If you define a public object in your managed C++ (Also called C++/CLI):

public ref class MyManagedClass{
. . .
}

and then reference the dll from your c# project, you'll be able to use the object just like you had defined it in c#.

Outras dicas

You can access C++ objects/dlls either by COM Interop or C++/CLI. Using C++/CLI you can create your own wrapper objects/classes which is directly usable in C#. Knowing both C++ and C#, the syntax will be somewhat familiar to you (and there are good resources online).

C++/CLI may require a bit more work as you need to write the CLI wrappers, but will keep things clearer in your C# code (my opinion).

This following article should get you started: Quick C++/CLI - Learn C++/CLI in less than 10 minutes

A more in-depth article: http://msdn.microsoft.com/en-us/magazine/cc163852.aspx

A code example (show casing the syntax) to make things more exciting, borrowed from above. Student is your C++ class, StudentWrapper is th CLI wrapper to be used in your C# code:

public ref class StudentWrapper
{
private:
  Student *_stu;
public:
  StudentWrapper(String ^fullname, double gpa)
  {
    _stu = new Student((char *) 
           System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(
           fullname).ToPointer(), 
      gpa);
  }
  ~StudentWrapper()
  {
    delete _stu;
    _stu = 0;
  }

  property String ^Name
  {
    String ^get()
    {
      return gcnew String(_stu->getName());
    }
  }
  property double Gpa
  {
    double get()
    {
      return _stu->getGpa();
    }
  }
};
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top