0

I have a class created in C#, and I want to reference a C++ class that was created. When I try to create an instance of the C++ class in C#, it can see the default constructor, but it can't see the constructor with arguments.

C++ cppClass code:

cppClass:: cppClass(const char* charArray)

C# code:

cppClass temp = new cppClass(); // <-- This works.
cppClass temp = new cppClass("Take 2"); // <-- This does not work.

When I use the second code, I get cppClass does not contain a constructor that takes 1 argument.

I've set up the reference from the C# project to the C++, it can see the structs and the default constructor, but it can't see the one with arguments. Do I need to write a wrapper to be able to pass arguments?

Bob.
  • 3,894
  • 4
  • 44
  • 76
  • What are the arguments of your C++ struct constructor? You wouldn't be able to pass `std::string` references from C#, for instance. – zneak Jul 03 '12 at 17:52
  • @zneak I added in the constructor code. – Bob. Jul 03 '12 at 18:09
  • @mydogisbox Not that I know of, the code is part of an old program that I am trying to port into C#, without having to re-write all the code. – Bob. Jul 03 '12 at 18:10
  • 1
    @Bob : I think his point is that you can port it to _.NET_ without rewriting all the code, by way of C++/CLI. Why is C# specifically necessary? – ildjarn Jul 03 '12 at 18:23
  • You cannot use C++ classes in C#, simple as that. If the first line compiles in C# then either you have defined that class elsewhere in C# code or you are using C++/CLI. – Konrad Rudolph Jul 03 '12 at 18:27
  • Is the constructor `public`? class members (unlike struct members) are `private` by default. – D Stanley Jul 03 '12 at 18:28
  • @Konrad : It's impractical, but _technically_ it's possible by way of `#pragma make_public` and P/Invoke specifying mangled names. – ildjarn Jul 03 '12 at 18:34

1 Answers1

1

If that is your actual code then the constructor is private by default. Check the header to make sure the constructor is in a public section:

public: 
   cppClass::cppClass(const char*)
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • Modified to proper c++ syntax. – D Stanley Jul 03 '12 at 18:40
  • Okay, I did that, but it still doesn't show up and I still get the same error. In Visual Studio 2010, I can see the constructor exists and public, and that the variables inside are private, but the metadata file created is declaring it as a struct without anything in it. – Bob. Jul 03 '12 at 19:06
  • 1
    try changing the `const char*` to `System::String^` (managed pointer to a string). You'll need to marshal the string if you want to use it as a char* but it's not terrible. There's a basic overview of marshalling on MSDN at http://msdn.microsoft.com/en-us/library/bb384865.aspx. – D Stanley Jul 05 '12 at 21:52
  • Thanks! I think that's what I'm going to do for now, no point re-writing the code (at this moment). – Bob. Jul 09 '12 at 11:43