我现在再利用modelica实现udp通信 ,我发数据使用了一个cjson的库,但是在openmodelica的仿真里面会出现找不到cjson(D:\OPENMO~1\tools\msys\mingw64\bin\ld: �Ҳ� -lcJSON)的问题,我使用的是windows系统,下面是我出现的问题和modelica代码以及c代码


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib") // Winsock库
#include "cJSON.h" // 确保cJSON头文件路径正确
#define PUB_SERVER_UDP_PORT 5554
#define PUB_SERVER_UDP_IP "127.0.0.1"
#define PUB_BUFFER_UDP_SIZE 4096
static SOCKET pubsockfd; // 改为Windows套接句柄类型
static struct sockaddr_in pubservaddr;
static int IsPubSocketCreated = 0;
void initialize_pub_sockets() {
// 初始化Winsock
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
fprintf(stderr, "WSAStartup failed: %d\n", WSAGetLastError());
exit(1);
}
// 创建UDP套接字
pubsockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (pubsockfd == INVALID_SOCKET) {
fprintf(stderr, "socket creation failed: %d\n", WSAGetLastError());
WSACleanup();
exit(1);
}
// 配置服务器地址
memset(&pubservaddr, 0, sizeof(pubservaddr));
pubservaddr.sin_family = AF_INET;
pubservaddr.sin_port = htons(PUB_SERVER_UDP_PORT);
if (InetPtonA(AF_INET, PUB_SERVER_UDP_IP, &pubservaddr.sin_addr) != 1) {
fprintf(stderr, "Invalid address: %d\n", WSAGetLastError());
closesocket(pubsockfd);
WSACleanup();
exit(1);
}
IsPubSocketCreated = 1;
}
void cleanup_pubsockets() {
closesocket(pubsockfd); // Windows专用关闭函数
WSACleanup(); // 清理Winsock资源
}
void pubdata(char* keyname, int array_length, const double* pubarray) {
if (IsPubSocketCreated == 0) {
initialize_pub_sockets();
}
// 创建JSON对象
cJSON *jsonArray = cJSON_CreateArray();
for (int i = 0; i < array_length; ++i) {
cJSON_AddItemToArray(jsonArray, cJSON_CreateNumber(pubarray[i]));
}
cJSON *jsonRoot = cJSON_CreateObject();
cJSON_AddItemToObject(jsonRoot, keyname, jsonArray);
// 生成JSON字符串
char *jsonStr = cJSON_PrintUnformatted(jsonRoot);
if (!jsonStr) {
fprintf(stderr, "JSON serialization failed\n");
cJSON_Delete(jsonRoot);
exit(1);
}
// 发送数据(Windows使用int表示地址长度)
int addr_len = sizeof(pubservaddr);
if (sendto(pubsockfd, jsonStr, strlen(jsonStr), 0,
(struct sockaddr*)&pubservaddr, addr_len) == SOCKET_ERROR) {
fprintf(stderr, "sendto failed: %d\n", WSAGetLastError());
free(jsonStr);
cJSON_Delete(jsonRoot);
exit(1);
}
// 清理资源
cJSON_Delete(jsonRoot);
free(jsonStr);
}
// 测试主函数(重命名为main)
int main(int argc, char* argv[]) {
double test_data[] = {1.23, 4.56, 7.89};
pubdata("test_data", 3, test_data);
// 等待2秒确保数据发送
Sleep(2000);
cleanup_pubsockets();
return 0;
}