I need to be able to call some very old C functions from a form application. What I found on line was to use 'extern "C"' to let Visual Studio know how to handle the calling parameters. But I'm getting a compiler error and not sure where it is coming from.

I changed the Form1.h file as:

extern "C" char *doit();
	private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
//				 richTextBox1->Text="Button Hit\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7";
				 richTextBox1 = doit();
			 }
	private: System::Void richTextBox1_TextChanged(System::Object^  sender, System::EventArgs^  e) {
			 }

and the actual doit.c file as:

#include <stdio.h>

char *xyz = 0;

extern "C" char *doit()
{
	xyz = calloc(1, 1024);
	sprintf(xyz,"Button Hit\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7");
	return xyz;
}

The error I'm getting is:

Command line error D8045: cannot compile C file '.\doit.c' with the /clr option File cl

Can this even be done?

If so, can someone point me to an example.

Thanks

Do you have the original source code?
If so, change the extension to .cpp, add the source to your project, make sure you're using warning level 4 and re-compile.

After you fix all of the (now-known-as) bugs, you'll be finished.

Do you have the original source code?
If so, change the extension to .cpp, add the source to your project, make sure you're using warning level 4 and re-compile.

After you fix all of the (now-known-as) bugs, you'll be finished.

Thanks, that did work. The hardest piece of the puzzle was finding the "gcnew" keyword.

doit.CPP

#include "stdafx.h"

#include "stdio.h"
#include "stdlib.h"

char *xyz = 0;

extern "C" char *doit()
{
	xyz = (char *)calloc(1, 1024);
	sprintf(xyz,"Button Hit\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7");
	return xyz;
}

and the change to form1.h

extern "C" char *doit();

moved outside namespace:

And the button1_Click code is now:

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
//				 richTextBox1->Text="Button Hit\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7";
				 char *p = doit();

				 richTextBox1->Text = gcnew String(p);
			 }

It compiles and runs now

Thanks


Update: Simplify the code:

You can combine the lines

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
//				 richTextBox1->Text="Button Hit\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7";
				 richTextBox1->Text = gcnew String(doit());
			 }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.