查了一些相关资料MATLAB的通信最好用32位的MATLAB,对于是不是64位的系统无所谓,但是一定要装32位的MATLAB,否则生成不了mexw32文件
1.通过udp编写的c与matlab混合编写的点c文件如下:
Send.c
#include "mex.h"
#include <Winsock2.h>
#include <stdio.h>
#define SERVER_ADDRESS "172.19.207.221"
#define PORT 5150
#define MSGSIZE 100
#pragma comment(lib, "ws2_32.lib")
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
WSADATA wsaData;
SOCKET sClient;
SOCKADDR_IN server;
char *DATAin;
int i;
int N;
char szMessage[MSGSIZE];
DATAin=mxArrayToString(prhs[0]);
N=mxGetN(prhs[0]);
for(i=0;i<N;i++)
{
szMessage[i]=DATAin[i];
}
szMessage[N] = '\0';
WSAStartup(0x0202, &wsaData);
sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
memset(&server, 0, sizeof(SOCKADDR_IN));
server.sin_family = PF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = inet_addr(SERVER_ADDRESS);
connect(sClient, (struct sockaddr *) &server, sizeof(SOCKADDR_IN));
//Sending data
send(sClient, szMessage, strlen(szMessage), 0);
closesocket(sClient);
WSACleanup();
}
Receive.c
#include "mex.h"
#include <Winsock2.h>
#include <stdio.h>
#define PORT 5150
#define MSGSIZE 100
#pragma comment(lib, "ws2_32.lib")
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs [])
{
WSADATA wsaData;
SOCKET sListen;
SOCKET sClient;
SOCKADDR_IN local;
SOCKADDR_IN client;
char szMessage[MSGSIZE];
int ret;
char *DATAout;
int i;
int iaddrSize = sizeof(SOCKADDR_IN);
WSAStartup(0x0202, &wsaData);
sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
local.sin_family = AF_INET;
local.sin_port = htons(PORT);
local.sin_addr.s_addr = htonl(INADDR_ANY);
bind(sListen, (struct sockaddr *) &local, sizeof(SOCKADDR_IN));
listen(sListen, 1);
sClient = accept(sListen, (struct sockaddr *) &client, &iaddrSize);
mexPrintf("Accepted client:%s,%d\n", inet_ntoa(client.sin_addr),ntohs(client.sin_port));
//Receiving data
ret = recv(sClient, szMessage, MSGSIZE, 0);
szMessage[ret] = '\0';
mexPrintf("Received [%d bytes]: %s\n", ret, szMessage);
DATAout=mxCalloc(ret,sizeof(char));
for(i=0;i<ret;i++)
{
DATAout[i]=szMessage[i];
}
DATAout[ret]='\0';
plhs[0]=mxCreateString(DATAout);
closesocket(sClient);
closesocket(sListen);
WSACleanup();
}
通过mex -setup选择编译器后的编译结果如下:
没有编译成功,通过mex -v -g Send.c命令后结果如下:
然后重新选择编译器,重新编译如下:
编译成功了,没想到编译成功了,由于时间原因不做详细解释,需要注意的是有些中文版软件自带的编译器是优化后的编译器,MATLAB可能检测不出来,集体如何修改,请看我的其他博客。