C ++ DLL call from C #
I want to use a C ++ DLL from C #. C ++ DLL is a win32 console application. I have successfully called it and want to process the data I have from C ++ to C #. However, the C # application exits the DLL execution and this line:GetArrayFromDLL();
I am new to C # and Visual C ++. Can anyone give some suggestions?
thank
namespace ConsoleApplication1
{
class Program
{
[DllImport("Lidar_DataCal_CDLL.dll")]
public static extern void GetArrayFromDLL();
static void Main(string[] args)
{
Console.WriteLine("This is C# program");
GetArrayFromDLL();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
It is a DLL written in a win32 application.
extern "C"
{
__declspec(dllexport) void GetArrayFromDLL()
{
/// Reading hex from a file
FILE * pFile;
FILE * f;
signed int array_data[81],array_data1[81],i;
double fangle,fsin,fcos,fangle_rad;
double afx[81],afy[81];
int px,py;
char file_read[20] = "scandataset1.txt";
char file_write[20] = "xycordinates1.txt";
pFile = fopen ( file_read,"a+");
if (pFile != NULL)
{
for (i=0;i<80;i++)
{
char buffer[3];
fscanf (pFile, "%x",&array_data[i]);
sprintf ( buffer ,"%d", array_data[i]);
printf ( "I have read: %s \n\n", buffer);
array_data1[i] = atoi(buffer);
// finding angle
fangle = 20 -( (i+1-1)*0.5);
fangle_rad = (PI*fangle/180);
fsin = -sin(fangle_rad);
fcos = cos(fangle_rad);
afx[i] = array_data[i] * fsin;
afy[i] = array_data[i] * fcos;
// printf ("X: %lf and Y: %lf \n\n",afx[i],afy[i]);
f = fopen(file_write,"a+");
if(f != NULL);
fprintf(f,"%lf %lf\n",afx[i],afy[i]);
fclose (f);
}
}
else
{
printf("Error opening fail");
}
fclose (pFile);
}
}
source to share
The main problems I have had to face when using native C ++ in C # are marshaling problems . check to make sure you don't have them. and since you said the dll is executing just fine, the only problem that might come up is with the return type of the functions. C code cannot be the culprit, it must be a dll.
Also try specifying the calling convention and entry point when importing the dll
source to share
Basically there are only two simple approaches to calling C ++ methods. Either create C-callable wrappers (functions) around your object-oriented interface, making it language independent but not always exactly pretty or maintainable, or you can use an object-oriented language glue between C # and C ++.
In .NET 1.1, the glue language was C ++ driven (it's gone these days).
Its successor language, which is probably the best choice for you, is C ++ / CLI. This language is best used only for a relatively thin layer between managed and unmanaged worlds, which it can unify pretty well.
(Practically speaking: if you are using VS2010 and set up .NET older than 4 for whatever reason, adding C ++ / CLI code will force you to install VS 2008 on your system as well, but you can still fully use the VS2010 IDE for all three languages.)
source to share