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:
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?
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#.
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();
}
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With