Attaching images to posts manually (i.e. with custom code, without the use of an API)

Attachments are posts of type attachment with the parent field set to the post ID they are attached to.
The simplest way to see how this works is to look at the attachment functions in core code, /wp-includes/post.php.