首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mac Office 2011 VBA和Dylib

Mac Office 2011 VBA和Dylib
EN

Stack Overflow用户
提问于 2012-03-23 11:28:33
回答 1查看 602关注 0票数 1

我正在开发Mac OS中的Word 2011插件。目前,我需要在VBA Macro中编写代码,以便从另一个应用程序检索字符串(通过套接字通信)。因此,基本上在Windows中,我可以简单地创建一个DLL,它帮助我与其他应用程序进行套接字通信,并将字符串值返回到VBA宏。

然而,在Mac中,我能够构建一个.dylib (用C语言)并使用VBA与dylib通信。但是,我在返回字符串时遇到了问题。我的简单C代码类似于: char * tcpconnect(char*参数) {}

首先,它总是包含Chr(0)字符。其次,我怀疑这个C函数将无法处理Unicode字符串。

你们有什么经验或者类似的例子吗?

谢谢,

大卫

EN

回答 1

Stack Overflow用户

发布于 2014-07-30 03:08:15

我最初的帖子是试图使用malloc()来模仿SysAllocStringByteLen(),但是当Excel试图释放返回的内存时,这将失败。使用Excel分配内存解决了这个问题,而且代码也更少,例如:

在test.c中:

代码语言:javascript
复制
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define LPCSTR const char *
#define LPSTR char *
#define __declspec(dllexport)
#define WINAPI

char *saved_string = NULL;
int32_t saved_len = -1;

#define _CLEANUP if(saved_string) free(saved_string)

__attribute__((destructor))
static void finalizer(void) {
  _CLEANUP;
}

int32_t __declspec(dllexport) WINAPI get_saved_string(LPSTR pszString, int cSize) {
  int32_t old_saved_len = saved_len;
  if(saved_len > 0 && cSize >= saved_len)
    strncpy(pszString, saved_string, saved_len);
  if(saved_string) {
    free(saved_string);
    saved_string = NULL;
    saved_len = -1;
  }
  return old_saved_len;
}

int32_t __declspec(dllexport) WINAPI myfunc(LPCSTR *pszString) {
  int len = (pszString && *pszString ? strlen(*pszString) : 0);
  saved_string = malloc(len + 5);
  saved_len = len + 5;
  sprintf(saved_string, "%s%.*s", "abc:", len, *pszString);
  return saved_len;
}

使用以下命令编译上面的代码

代码语言:javascript
复制
gcc -g -arch i386 -shared -o test.dylib test.c

然后,在一个新的VBA模块中,使用下面的代码并运行"test",这将在字符串"hi there“前面加上"abc:”,并将结果输出到调试窗口:

代码语言:javascript
复制
Public Declare Function myfunc Lib "<colon-separated-path>:test.dylib" (s As String) As Long
Public Declare Function get_saved_string Lib "<colon-separated-path>:test.dylib" (ByVal s As String, ByVal csize As Long) As Long

Option Explicit

Public Function getDLLString(string_size As Long) As String
    Dim s As String
    If string_size > 0 Then
        s = Space$(string_size + 1)
        get_saved_string s, string_size + 1
    End If
    getDLLString = s
End Function

Public Sub test()
Debug.Print getDLLString(myfunc("hi there"))
End Sub
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9833808

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档