views:

75

answers:

2

I'm getting to know Mono development in Linux, in baby steps. I'm trying to call Linux C libraries. This page, in theory, tells me how, but when I type the code below in MonoDevelop 2.2.2 (Fedora 13), I get a "Parsing Error (CS8025)" in "private static extern int getpid();". Moreover, the help system doesn't work.

EDIT: I just had to move the DllImport into the class for it to build, but now when I run it I get the following:

Unhandled Exception: System.DllNotFoundException: /usr/lib/libc.so
  at (wrapper managed-to-native) LinuxCaller.MainClass:getpid ()
  at LinuxCaller.MainClass.Main (System.String[] args) [0x00000] in <filename unknown>:0 

EDIT II, THE SEQUEL: libc.so is weird in Fedora. It's not the real libc, it only contains the text below. I used "libc.so.6" instead and everything works now.

/* GNU ld script
   Use the shared library, but some functions are only in
   the static library, so try that secondarily.  */
OUTPUT_FORMAT(elf32-i386)
GROUP ( /lib/libc.so.6 /usr/lib/libc_nonshared.a  AS_NEEDED ( /lib/ld-linux.so.2 ) )

The (now corrected and working) code:

using System;
using System.Runtime.InteropServices;

namespace LinuxCaller
{
    class MainClass
    {
        [DllImport("libc.so.6")]
        private static extern int getpid();

        public static void Main (string[] args)
        {
            Console.WriteLine ("Hello World from process {0}!", getpid());
        }
    }
}
+8  A: 

Function definitions cannot appear in the namespace scope in C#. This includes DLL import definitions. To fix this just move the function definition inside a type.

class MainClass {
  [DllImport("libc.so")]
  private static extern int getpid();

  ...
}
JaredPar
It builds now, but it doesn't find libc.so -- see above.
JCCyC
@JCCyC is libc.so at the given path and accessible to the process?
JaredPar
Yes, but intriguingly, it only has 238 bytes. Eek. It contains just some text! I used "libc.so.6" instead and it works now.
JCCyC
+2  A: 

If you just need to access some common *nix system calls, check out the Mono.Unix namespace which provides wrappers around a lot of functions.

http://www.go-mono.com/docs/index.aspx?link=N%3aMono.Unix

jpobst
Actually what I need is to call some UNcommon functions in third-party libraries, but that is indeed useful information.
JCCyC