How to declare constant lines for use in both an unmanaged C ++ dll and a C # application?

Enraged, I pass my constant constant values ​​from my C ++ to my C # when I run it through a callback, but I'm wondering if there is a way to define them in the C ++ header file, which I can also refer to in C #.

I already do this with listings, as they are easy. I include the file both in my C ++ library project (via the .h file with the pragma once at the top), and my C # application (as a link):

#if _NET public #endif enum ETestData { First, Second }; 

I know this sounds dirty, but it works :)

But ... how can I do the same with string constants - initially I think the syntax is too different between platforms, but maybe there is a way?

Using smart syntax involving #if _NET, #defines, etc.

Using resource files?

Using a C ++ / CLI library?

Any ideas?

+7
c ++ string c # managed unmanaged
source share
2 answers

Call me funny, but I think the best way to do this is to use C ++ / CLI and C ++.

This allows you to include the same lines in two different contexts and let the compiler do the magic. This will give you arrays of strings

 // some header file L"string1", L"string2", L"string3", // some C++ file static wchar_t*[] string = { #include "someheaderfile.h" }; // in some C++/CLI file array<String^>^ myArray = gcnew array<String^> { #include "someheaderfile.h" }; 

otherwise, you can use the C preprocessor directly:

 // in somedefineset #define SOME_STRING_LITERAL L"whatever" // in some C++ file #include "somedefineset.h" const wchar_t *kSomeStringLiteral = SOME_STRING_LITERAL // in some C++/CLI file literal String ^kSomeStringLiteral = SOME_STRING_LITERAL; 
+1
source share

The C # string constant will take the form:

 public const string MyString = "Hello, world"; 

I think the preferred way in C ++ is:

 const std::string MyString ="Hello, world"; 

string in C # is just an alias for the .NET type, string . One way to do this is to do C ++ #define:

 #define String const std::string 

And your general code would look like this:

  // at the beginning of the file #if !_NET #define String const std::string #endif // For each string definition #if _NET public const #endif String MyString = "Hello, world"; 

I have to admit that I have not tried it, but it looks like it will work.

+2
source share

All Articles