MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: A little C program calling MathLink

  • To: mathgroup at smc.vnet.net
  • Subject: [mg105190] Re: [mg105165] A little C program calling MathLink
  • From: 董理 <dongli2020 at gmail.com>
  • Date: Tue, 24 Nov 2009 05:46:30 -0500 (EST)
  • References: <200911231151.GAA21809@smc.vnet.net>

¶­Àí дµÀ:
> Hi, all,
>
> I am learning how to call MathLink in C program, and I wrote a little
> one as following:
>
> "
> #include <stdio.h>
> #include <string.h>
> #include "mathlink.h"
>
> int main(void)
> {
> MLINK link;
> MLEnvironment env;
> int packet;
>
> int argc = 4;
> char * argv[5] = {
> "-linkname",
> "math -mathlink",
> "-linkmode",
> "launch",
> NULL
> };
> char user_msg[10];
> const char * math_msg;
>
> printf("What do you want to say to Mathematica? (10 characters only!)\n> ");
> scanf("%s", user_msg);
>
> /* setup connection with MathLink */
> env = MLInitialize(NULL);
> if(env == NULL) {
> printf("MLInitialize: internal error\n");
> return -1;
> }
> link = MLOpen(argc, argv);
> if(link == NULL) {
> printf("MLOpen: internal error\n");
> return -1;
> }
>
> /* check validity of connection */
> while(!MLReady(link)) continue;
> if(MLConnect(link) == 0) {
> printf("MathLink connection failed\n");
> return -1;
> }
>
> /* sending packet to MathLink */
> MLPutFunction(link, "EvaluatePacket", 1);
> MLPutFunction(link, "Print", 1);
> MLPutString(link, user_msg);
> MLEndPacket(link);
>
> /* receiving packets from MathLink */
> while((packet = MLNextPacket(link)) && packet != RETURNPKT)
> MLNewPacket(link);
> if(!packet) {
> printf("packets receiving error\n");
> MLClearError(link);
> } else {
> if(!MLGetSymbol(link, &math_msg)) {
> printf("MLGetSymbol: internal error\n");
> return -1;
> }
> printf("Echo message from Mathematica:\n");
> printf("%s\n", math_msg);
> MLReleaseSymbol(link, math_msg);
> }
>
> /* disconnect with MathLink */
> MLClose(link);
> MLDeinitialize(env);
>
> return 0;
> }
> "
>
> the "math_msg" is NULL when it is printed. What's wrong with it? Thanks
> for help? : )
>
> Best regards,
>
> DONG Li
>
>   
Dear all,

I have fixed the problem. Because "Print" will not return a result of
calculation, so we should not wait for a RETURNPKT packet. What it
return is a TEXTPKT packet, so change the following snippet:

/* receiving packets from MathLink */
while((packet = MLNextPacket(link)) && packet != TEXTPKT)
MLNewPacket(link);
if(!packet) {
printf("packets receiving error\n");
MLClearError(link);
} else {
if(!MLGetString(link, &math_msg)) {
printf("MLGetString: internal error\n");
return -1;
}

PS: The document in Mathematica about MLNextPacket is wrong in writing
"TEXTPKT" as "TEXTPACKET".

Best regards,

DONG Li


  • Prev by Date: Re: More Efficient Method
  • Next by Date: Re: how to read in a number in hex and convert it to
  • Previous by thread: A little C program calling MathLink
  • Next by thread: Re: A little C program calling MathLink