Click to See Complete Forum and Search --> : Calling "C" function with variable number of arguments


reptile
November 30th, 2003, 05:18 PM
My question is about calling external "C" function with variable number of arguments.
I know how to call "C" function from msvcrt library.
For example if we want to call


int puts( char * s )

"C" function we must code something like that (from .NET documentation)


[DllImport("msvcrt", EntryPoint="puts")]
extern "C" int puts( [MarshalAs(UnmanagedType::LPStr)] String * );


Everything goes OK. But what I gotta do to call printf/sprintf like functions, functions with variable number of arguments.

When I code


[DllImport("msvcrt", EntryPoint="sprintf")]
extern "C" int sprintf( [MarshalAs(UnmanagedType::LPStr)] String *, [MarshalAs(UnmanagedType::LPStr)] String *, ... );


an exception occures!!!

Does anybody know? Help.

Rafael Miguel
December 15th, 2003, 12:30 PM
Did you try to use malloc function?


This function is used for allocate space in memory for variables.

Ex:

main(){
int *arrayint,i; //declare pointer variable
arrayint = (int *)malloc(sizeof(int) * 5); //allocate array of lenght 5
for (i = 0;i < 5;i++){
arrayint[i] = i;
printf("%d",i);
}
free(arrayint);
}

I wanted to be helpful.

Rafael Miguel

Rafael Miguel
December 15th, 2003, 12:31 PM
Oh Sorry.

I posted in wrong topic.

Rafael Miguel

reptile
December 15th, 2003, 03:32 PM
The problem is not in code that I'm using. The problem is exactly in calling sprintf function, and exactly because of shown way of its usage.
And nothing else.

10thPower
December 27th, 2003, 09:09 PM
A question : why are you trying to write a managed application/assembly using stdio calls ?

Just write a normal MFC application or a COM dll and you won't have any problems.

If you're trying to write a managed assembly then you should use .NET functions with System::String.

It appears you're trying to avoid learning .NET when using managed code. That's like trying to learn to drive a car by riding a bycicle.

The two are not mutually exclusive but I've always used Visual C++.NET to inter-operate between IUnknown-based COM dlls and .NET applications written in C# or VB.NET.

If you're wanting to write managed code, then use managed code to do it.

Convert first, and then use the existing framework SDK to do your manipulation.

Unfortunately, you can't really, at least in my experience, go half .NET.

10thPower.